Next.js Discord

Discord Forum

Proper auth flow with expressjs backend?

Unanswered
EXILE posted this in #help-forum
Open in Discord
I'm currently working at a startup (unpaid) to get experience and the codebase is a bit of a mess. I'm trying my best to fix a lot of issues.

Our express backend is handling auth via an access+refresh token through cookies.
Our api lives on api.domain.com and our frontend is currently on staging.domain.com. So we've set the cookie options to .domain.com

Every endpoint just auto refreshes the access token if it doesn't exist or is expired etc... so we only really need to pass the refresh token to the backend.
We're doing basic refresh token checks in middleware to redirect to login if no cookie. If there's a cookie then let them visit protected routes, if there's a cookie and they visit auth pages then redirect to the dashboard.
The issue is when they have invalid cookies because on our pages we're hitting an endpoint to get the user info if that fails then it redirects to login. It ends up being an infinite loop due to this. I've tried clearing cookies but I'm unable to on the nextjs server. Not sure if that's due to RSC and us using a separate backend.

For redirecting we need to know if the user isVerified or isOnboarded to redirect them to the appropriate pages. I'm handling this again on the pages (rsc) but we get a flash of a loading.tsx. If we used middleware it would be a lot more smooth but that requires stuffing the jwt with more these extra fields (not sure if that's a bad idea or not) and then we would also have to share the same jwt secret with backend and frontend to verify this.

The whole system is a mess, but I just don't want to heavily refactor the backend as it will cause many merge conflicts and I'm also focused on the frontend at this time.
If we do need to refactor heavily then I'll handle it, but I just need an idea on the best approach.

1 Reply

The issue is when they have invalid cookies because on our pages we're hitting an endpoint to get the user info if that fails then it redirects to login. It ends up being an infinite loop due to this. I've tried clearing cookies but I'm unable to on the nextjs server. Not sure if that's due to RSC and us using a separate backend.
If it redirects to login, it shouldn't redirect back since cookie is invalid. If the redirect is caused due to middleware, exclude that route from middleware.ts

For redirecting we need to know if the user isVerified or isOnboarded to redirect them to the appropriate pages. I'm handling this again on the pages (rsc) but we get a flash of a loading.tsx. If we used middleware it would be a lot more smooth but that requires stuffing the jwt with more these extra fields (not sure if that's a bad idea or not) and then we would also have to share the same jwt secret with backend and frontend to verify this.
I don't think loading is a major problem, it is better than a blank screen