Next.js Discord

Discord Forum

How to prevent server layout UI before running redirect for logged in users

Unanswered
Azawakh posted this in #help-forum
Open in Discord
AzawakhOP
Hello! We are very close to finalizing a large migration from Gatsby to NextJS. Couple of precursor contextuals:
- We are deploying with Next export strategy using next@13.4.3
- We use app router

The problem:
We are currently using a <Script> component with beforeInteractive strategy to inject inline javascript that will redirect a user to the logged-in application when they meet the following criteria:

A) They visit the home / route
B) They have an auth cookie in their browser.

In Gatsby, we simply used onPreRenderHTML to inject this script, and when visiting the page, there was virtually zero rendering of anything - the user would simply be redirected very quickly into the application. However, in NextJS, using the Script with beforeInteractive strategy is resulting in users seeing a flash of the pre-rendered/pre-hydrated UI on the page before they are redirected to the logged in app. I have validated that this javascript injected with the Script component is indeed firing before anything else in the application, but sadly this isn't soon enough.

Are there any ways to redirect a user (using app directory with static export builds) such that when they meet the criteria outlined above, they will be instantly redirected like they were in Gatsby? I can't pinpoint what exactly Gatsby is doing to make that javascript run before anything else, but it seems NextJS is prioritizing serving the prerendered HTML before (or parallel to) the redirect script happening - and i'd really prefer to avoid implementing some kind of stateful logic whereby, for example, we prevent rendering the root layout children until we determine the user's auth state, since we prefer to keep our root layout Server rendered.

Any help at all would be greatly appreciated!

0 Replies