1

I'm currently working on a Next.js project, and I have used static export to improve performance and SEO. However, I've encountered an issue related to URL changes. I'd like to implement 301 redirect. so that search engines and users are redirected to the updated pages.

Any help, code snippets, or pointers to the right documentation would be greatly appreciated.

I have tried redirects in next.config.js and getServerSideProps but these methods are not supported in static export.

  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Aug 03 '23 at 08:22

1 Answers1

0

You can use window.location.pathname to set the path of the current url. Just place this code on the page you want to redirect from.

export default function Page() {
    if (typeof window !== "undefined") {
        window.location.pathname = "replacement_url"; 
    }

    return (
        ...
    );
}

I wrapped it in an if statement because React throws the following error when you try to use window.

    ReferenceError: window is not defined

MDN has some window.location documentation

mrtomblue
  • 118
  • 1
  • 11
  • middleware is also not supported in static export. https://nextjs.org/docs/pages/building-your-application/deploying/static-exports#unsupported-features – aman pandey Aug 04 '23 at 05:58
  • @amanpandey oh you're right. It also says that redirects are unsupported. Is switching to the AppRouter an option? Although middleware is unsupported for static exports in the AppRouter as well, but is only seems to mention redirects for static exports being unsupported in `nextjs.config.js` – mrtomblue Aug 04 '23 at 16:40
  • @amanpandey I think I found a solution and I updated my answer. Let me know if it works – mrtomblue Aug 04 '23 at 17:36
  • this is not 301 redirection. it will redirect the URL on the client side. – aman pandey Aug 09 '23 at 10:03
  • @amanpandey you're right, again. A similar [question](https://stackoverflow.com/q/13846738/17443354) has been asked before though, and [answered](https://stackoverflow.com/a/13846778/17443354), and I'm not sure that there is a work around for `static exports` if you need a server for `301 redirects` – mrtomblue Aug 10 '23 at 18:14