Next.js Discord

Discord Forum

JWT Authentication in Next.js 14 App Router (SSR) – Should We Use HttpOnly Cookies?

Unanswered
North Pacific hake posted this in #help-forum
Open in Discord
Avatar
North Pacific hakeOP
JWT Authentication in Next.js 14 App Router (SSR) – Handling HttpOnly Cookies

Our project is based on Next.js 14 App Router with SSR, and the API server is separately configured.
We are currently implementing a login feature where the server returns a JWT token via both the Set-Cookie header and a JSON response.

For security reasons, we are using HttpOnly cookies, but the issue is that the client needs to include this cookie in the Authorization header when making API requests.

Since HttpOnly cookies are not accessible from the browser, we are considering two possible approaches:

Using API Routes or Server Actions to retrieve the cookie and return it to the client
Using API Routes to read the cookie and forward the request to the API server
However, both approaches may introduce unnecessary Next.js server requests, which makes us question whether this is the right approach.

Would it be better to remove the HttpOnly option so the client can directly access the cookie?
Or is our current approach more appropriate from a security standpoint?

How have you handled authentication in similar cases?.

4 Replies

Avatar
Argentine hake
My suggestion would be to keep the cookies as httpOnly, use a wildcard cookie domain (.example.com) and ensure that every API/server you need to directly request from the browser is a subdomain of the cookie domain (api.example.com). That way your cookie should be secure and included in every request to your servers.
Avatar
Mallow bee
Using the Next.js backend to forward the requests is generally a good idea
This is called the backend-for-frontend pattern and counter intuitively it can sometimes be even faster than doing round trips directly from the user's browser
here's a little animation I made a while back

https://x.com/jacobmparis/status/1798518741048943100