Use Nextjs and external backend Setup

1 day ago 3
ARTICLE AD BOX

So I was trying to use Next.js and Express. I used Next.js only for frontend and SSR (ssr for some pages only). How can I add protected routes in Next.js in this two server setup?.

Normally, we would check cookies in Next.js middleware.

export async function proxy(req: NextRequest) { const path = req.nextUrl.pathname const cookies = req.cookies if(!cookies.requiredCookie){ //redirect} ..........

It was working well, but only in localhost/dev mode. In production, cookies are set by Express, which is now on a different domain from Next.js.
So cookies set by express is not allowed to send to Next.js (cookie domain rules in browser). Now if we use this setup, we can log in but still can’t view protected pages because no cookies are sent to the middleware.
Im stuck at this point.
I also found that we can rewrite requests from Next.js via Next config, but for normal api requests Next rewrite config doesnt pass the cookies. This makes express complain about no cookies were recieved.

Now I’m starting to think Next.js might not be a good fit for this two-server setup.

I also found that using the same domain with different subdomains helps. When setting cookies from Express, you can use .domain.com as the cookie domain. For example, app.domain.com and api.domain.com. However, configuring domains is not easy for everyone.

Read Entire Article