Skip to content

Commit b815438

Browse files
committed
Add error for redirect during prerendering
1 parent f730244 commit b815438

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Redirect During getStaticProps Prerendering
2+
3+
#### Why This Error Occurred
4+
5+
The `redirect` value was returned from `getStaticProps` during prerendering which is invalid.
6+
7+
#### Possible Ways to Fix It
8+
9+
Remove any paths that result in a redirect from being prerendered in `getStaticPaths` and enable `fallback: true` to handle redirecting for these pages.
10+
11+
### Useful Links
12+
13+
- [Data Fetching Documentation](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation)

packages/next/next-server/server/render.tsx

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -591,6 +591,13 @@ export async function renderToHTML(
591591
if (data.redirect && typeof data.redirect === 'object') {
592592
checkRedirectValues(data.redirect, req)
593593

594+
if (isBuildTimeSSG) {
595+
throw new Error(
596+
`\`redirect\` can not be returned from getStaticProps during prerendering (${req.url})\n` +
597+
`See more info here: https://err.sh/next.js/gsp-redirect-during-prerender`
598+
)
599+
}
600+
594601
if (isDataReq) {
595602
data.props = {
596603
__N_REDIRECT: data.redirect.destination,

test/integration/gssp-redirect/test/index.test.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,4 +212,42 @@ describe('GS(S)P Redirect Support', () => {
212212

213213
runTests()
214214
})
215+
216+
it('should error for redirect during prerendering', async () => {
217+
await fs.mkdirp(join(appDir, 'pages/invalid'))
218+
await fs.writeFile(
219+
join(appDir, 'pages', 'invalid', '[slug].js'),
220+
`
221+
export default function Post(props) {
222+
return "hi"
223+
}
224+
225+
export const getStaticProps = ({ params }) => {
226+
return {
227+
redirect: {
228+
permanent: true,
229+
destination: '/another'
230+
}
231+
}
232+
}
233+
234+
export const getStaticPaths = () => {
235+
return {
236+
paths: ['first', 'second'].map((slug) => ({ params: { slug } })),
237+
fallback: true,
238+
}
239+
}
240+
`
241+
)
242+
const { stdout, stderr } = await nextBuild(appDir, undefined, {
243+
stdout: true,
244+
stderr: true,
245+
})
246+
const output = stdout + stderr
247+
await fs.remove(join(appDir, 'pages/invalid'))
248+
249+
expect(output).toContain(
250+
'`redirect` can not be returned from getStaticProps during prerendering'
251+
)
252+
})
215253
})

0 commit comments

Comments
 (0)