Next.js Discord

Discord Forum

How to do redirects in static export?

Unanswered
Standard Chinchilla posted this in #help-forum
Open in Discord
Standard ChinchillaOP
It seems that the redirect hook doesn't work when exporting as a static site. Is there a workaround for this? I need to maintain state in zustand while redirecting as well. I am currently using the App Router.

4 Replies

I think the redirect that isn't supported in static export is the one from next.config.js: https://nextjs.org/docs/app/api-reference/next-config-js/redirects
if you tested the redirect() function with an exported app and it indeed didn't work, you could use the normal methods to redirect in the browser as the app will always run in the browser:
// Redirect overriding the history
window.location.replace("http://foo.bar");

// Redirect pushing to the history
window.location.href = "http://foo.bar";
Standard ChinchillaOP
its strange because it works when i run it with npx serve locally after building but when hosting it online it doesnt work
ill try your method and see how it goes
Standard ChinchillaOP
unfortunately both methods dont seem to be working (using router or location.href directly). I am really at a loss as to how to make it work.

Here is the code that I am currently using:
  const router = useRouter();
  const session = sessionStore(); // Just a zustand data store.

  useEffect(() => {
    if (session.data == null) {
      router.replace(
        `${Routes.login}?${buildRedirectUrlQueryParamsString(getURL())}`,
      );
    } else if (session.data!.session_user.role != UserRole.SystemAdmin) {
      router.replace(Routes.home);
    }
  }, [router, session]);

  if (
    session.data == null ||
    session.data!.session_user.role != UserRole.SystemAdmin
  ) {
    return null;
  }

  return (
    <Center>
      <p>This is the admin panel page.</p>
    </Center>
  );


my next config has output = export. what am i doing wrong?