乐闻世界logo
搜索文章和话题

How to redirect using getStaticProps?

1个答案

1

In Next.js, to implement redirection in getStaticProps, you must return a response containing a redirect object. Here's an example implementation of redirection in getStaticProps:

jsx
export async function getStaticProps(context) { // ... logic to determine redirection based on content availability // When redirection is required if (someCondition) { return { redirect: { destination: '/some-other-page', // target route for redirection permanent: false, // set to true for permanent redirection }, revalidate: 10, // optional for ISR in production }; } // ... other props return { props: {}, // normal page props // revalidate: 10, // optional for ISR in production }; }

The someCondition is a placeholder for your logic condition. If the condition evaluates to true, the function returns a redirect object, causing Next.js to redirect to the URL specified by destination. The permanent property indicates to the browser whether the redirection is permanent (true) or temporary (false). If set to true, browsers and search engines will cache the redirection.

Note that getStaticProps executes only during the build process, meaning the redirection logic must rely on information available at build time. For redirection based on per-request data, consider using getServerSideProps, which executes on every request.

2024年6月29日 12:07 回复

你的答案