Fix Error: Error: Error serializing `.data` returned from `getServerSideProps`. Reason: `undefined` cannot be serialized as JSON. in Next.js
This error occurs when getServerSideProps returns an object containing undefined values, which JSON.stringify cannot serialize. Next.js requires all props to be serializable. Fix it by replacing undefined values with null, filtering them out, or using JSON.parse(JSON.stringify(data)) to strip undefined fields before returning.
Reading the Stack Trace
Here's what each line means:
- at isSerializable (/app/node_modules/next/dist/server/render.js:284:15): Next.js checks that all values returned from getServerSideProps can be serialized to JSON before sending to the client.
- at renderToHTML (/app/node_modules/next/dist/server/render.js:897:13): The error is thrown during HTML rendering when the serialization check fails on the props object.
- at async DevServer.renderPageComponent (/app/node_modules/next/dist/server/base-server.js:1618:24): The page component's server-side rendering pipeline is interrupted by the serialization error.
Common Causes
1. Undefined field in database response
The database query returns an object with undefined fields that are passed directly as props without sanitization.
export async function getServerSideProps() {
const user = await prisma.user.findUnique({ where: { id: 1 } });
return {
props: { data: user } // user.bio may be undefined
};
}
2. Optional API response field
An external API returns optional fields as undefined instead of null, which fails serialization.
export async function getServerSideProps() {
const res = await fetch('https://api.example.com/profile');
const profile = await res.json();
return {
props: { data: { name: profile.name, avatar: profile.avatar } }
// avatar is undefined if not set
};
}
3. Date or function in props
Returning non-serializable types like Date objects or functions from getServerSideProps causes the same serialization error.
export async function getServerSideProps() {
const post = await getPost(1);
return {
props: { data: { ...post, createdAt: post.createdAt } }
// createdAt is a Date object
};
}
The Fix
Use JSON.parse(JSON.stringify(data)) to strip undefined values and convert Date objects to strings. This ensures all props are serializable. For more control, you can manually map fields and replace undefined with null.
export async function getServerSideProps() {
const user = await prisma.user.findUnique({ where: { id: 1 } });
return {
props: { data: user }
};
}
export async function getServerSideProps() {
const user = await prisma.user.findUnique({ where: { id: 1 } });
return {
props: {
data: JSON.parse(JSON.stringify(user))
}
};
}
Testing the Fix
import { getServerSideProps } from '@/pages/dashboard';
import { prismaMock } from '@/test/prisma-mock';
describe('getServerSideProps', () => {
it('returns serializable props even with undefined fields', async () => {
prismaMock.user.findUnique.mockResolvedValue({
id: 1,
name: 'Alice',
bio: undefined,
});
const result = await getServerSideProps({} as any);
const json = JSON.stringify(result.props.data);
expect(() => JSON.parse(json)).not.toThrow();
});
it('returns user data in props', async () => {
prismaMock.user.findUnique.mockResolvedValue({ id: 1, name: 'Alice', bio: 'Hello' });
const result = await getServerSideProps({} as any);
expect(result.props.data.name).toBe('Alice');
});
});
Run your tests:
npm test
Pushing Through CI/CD
git checkout -b fix/gssp-serialization-error,git add src/pages/dashboard.tsx src/pages/__tests__/dashboard.test.tsx,git commit -m "fix: sanitize getServerSideProps return value for JSON serialization",git push origin fix/gssp-serialization-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test -- --coverage
- run: npm run build
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
import { initBugStack } from 'bugstack-sdk'
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the test suite locally to confirm props are serializable.
- Open a pull request with the serialization fix.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify the page loads correctly in staging.
Frequently Asked Questions
BugStack serializes the return value of getServerSideProps in tests, validates all fields are JSON-compatible, and confirms the build succeeds before marking it safe.
Every fix is delivered as a pull request with full CI validation. Your team reviews and approves before anything reaches production.
Yes. Both getStaticProps and getServerSideProps require serializable return values. The same fix applies to both functions.
For typical page props (a few KB), it is fast enough. For very large datasets, consider selecting only the fields you need or using a library like superjson.