r/reactjs • • 22d ago

Discussion How do you usually secure your Next.js web apps?

Hey everyone!

To my knowledge, storing access tokens in localStorage can be risky because of XSS attacks

Yesterday, I came across this document: How to implement authentication in Next.js.

I decided to give it a try. Here's what I've come up with so far

  1. Use OpenSSL to generate an RSA key pair for verifying access tokens. The private key stays on the backend, while the public key is exposed to the frontend.
  2. Authentication: When a user successfully logs in, the backend sets the access token in cookie.
  3. In frontend, use Jose lib to fetch public key, and verify access token
  4. Implemented a Data Access Layer (DAL) with two functions:
  • verifySession to verify the accessToken and redirect users to /login if the token is missing or invalid.
  • checkRoles to check user roles to make sure users can't access pages they're not supposed to.

The doc also suggests adding a DTO layer, but I skipped it since I'm using OpenAPI specs and TypeScript type generation.

I'd really appreciate it if you could share your thoughts:

Do you see any potential security issues or problems with this flow?

Is there anything you would approach differently?

4 Upvotes

21 comments sorted by

9

u/yksvaan 22d ago

Separate backend that handles all auth, business logic and in general everything not public. 

Tokens should only be in httponly cookies unless there's a very good reason to do otherwise. 

If you need to have backend for frontend, it should only be limited to doing some basic token validity checks with the public key and other sanity checks. 

1

u/Neat_Living_6765 21d ago

Thanks for sharing your thoughts!

Yes, the access token is stored in a cookie with all the security flags enabled: HttpOnly, Secure, and SameSite=Lax.

Currently, I'm handling token verification and role checks (authorization) on both the backend and frontend.

4

u/amayle1 21d ago

Why would you need to verify the signature of the Jwt on the front end? That’s not even secure, somebody could just strip that JavaScript out.

You sign the JWT with your private key when you issue it. Your backend then verifies the signature using your public key upon receiving requests.

1

u/Neat_Living_6765 21d ago

I'm verifying the JWT signature and implementing role-based authorization on both the frontend (Next.js) and backend (Node.js).

All verification and authorization checks on the frontend are performed in Server Components, not Client Components. My goal is to improve the UX and restrict page access based on user roles. In other words, I want to prevent unauthorized users from accessing restricted pages before they are blocked again when making API calls.

I generated an RSA key pair on the backend and kept the private key secure. The public key is exposed through an API, and the frontend fetches it using the built-in methods provided by the jose lib

1

u/Pretend_Football6686 16d ago

We have a list of security checks we do on the front end. But it’s all just for show. It’s hides things you don’t have permissions too, not because it secures it but because then you can’t click on it or use it and get nasty 403 errors. If a user “hacks” the front JavaScript they just see server errors or maybe even a completely failed to render page.
Basically if you don’t have permissions to look at a screen we hide it from the menu or disable parts of it. If you force your way past your met with a 403 as soon as it tried to get any data for it.

We assume (because it’s 100% true) all the front end security is compromised and all real security checks are done on the backend. We don’t even bother to verify if the jwt was issued by the right place on the front end. We even have a script we give to QA that they can run which sets that state as if their user has every permission and right. Then they can test if pages fail gracefully if the user lack permissions and double check the server side is doing its thing as well.

2

u/danielraison 19d ago

Don't fetch the public key on every request. Expose it as a JWKS (/.well-known/jwks.json) and use jose's createRemoteJWKSet. It caches the key and picks the right one by kid, so you can rotate keys later without redeploying the frontend.

Check more than the signature. Pass algorithms: ['RS256'], issuer and audience to jwtVerify. Pinning the algorithm closes off the classic algorithm-confusion tricks, and issuer/audience stop a token issued for another service from working on yours.

Signature-only checks can’t revoke anything. If you disable a user or change their role, their current token stays valid until it expires, roles included. Keep the access token short (5 to 15 minutes) and put the refresh token in a separate httpOnly cookie, ideally with a Path limited to the refresh endpoint so it isn’t sent with every request.

Server Actions are public POST endpoints. Checking the page doesn't protect the actions it uses. Call verifySession/checkRoles inside each action, the same way you would in a route handler.

Don't make middleware your only check. CVE-2025-29927 let anyone skip Next.js middleware entirely with a single header. It's patched now, but it's a good reminder of why the DAL approach in the docs is the right one.

1

u/Neat_Living_6765 17d ago

Thanks so much for sharing those valuable thoughts!

Yes, I'm currently using createRemoteJWKSet. I've also checked the algorithms with ['RS256'] and added the extra issuer and audience to jwtVerify, just like you suggested.

Next up, I'm going to implement a refresh token along with a path-limited route.

For the frontend side, I'm using TanStack Query. I've set up a views folder containing full-page UIs that handle fetching and mutations via TanStack Query. Then, I just import those page views into the server component page.tsx files inside the app folder, which keeps the session verification and role checks there, like this:

  await connection();
  await verifySession();
  await requireRole("admin");
  return <MyPageView />;

Just to give you a bit of context: my backend is a separate Node.js codebase, and the frontend is built with Nextjs. Right now, I'm handling token verification and role-based authorization on both sides, but on the frontend, those checks are really just there for UX and user navigation.

6

u/CesnaitisSwitlana 16d ago

If your cookie is httpOnly like it should be, your frontend cant even read the token to verify it with Jose. do the token check inside your server components or middleware instead of the client. I use npx slices for my auth setup now so I dont mess up the plumbing, but regardless never trust client side role checks anyway.

1

u/Alarming_Ad_257 21d ago

All good but just one thing if the cookie is httpOnly, frontend JS cant read it, so step 3 doesnt really work. And if it’s not httpOnly, you’ve reopened the XSS problem you were trying to avoid.

1

u/Neat_Living_6765 21d ago

Yes, the access token is stored in a cookie with all the security flags enabled: HttpOnly, Secure, and SameSite=Lax.

Currently, I'm handling token verification and role checks (authorization) on both the backend and frontend.

HttpOnly prevents JavaScript running in the browser from accessing the cookie. I read it on a Next.js server component

import { cookies } from 'next/headers'

const token = (await cookies()).get('accessToken')?.value

2

u/Alarming_Ad_257 21d ago

Yes, reading it in server components makes sense. One small thing: wrap verifySession in React’s cache() so it only runs once per request even if multiple components call it. And keep auth checks out of layout.tsx. Layouts don’t re-render on client navigation, so a check there can get skipped.

2

u/maksymkoval 21d ago

Looks solid overall. Two things I'd check:

  1. Make the cookie HttpOnly, Secure and SameSite=Lax. With HttpOnly, client JS can't read the token at all, so verify it on the server instead (DAL in server components, route handlers, middleware).
  2. Treat any check in the browser as UX only. The real authorization has to happen on the server for every request and server action, because client code can be bypassed.

1

u/Old_Elderberry1392 21d ago

Drop the client-side verification step entirely. An httpOnly cookie is unreadable by JavaScript so that code path is physically impossible to execute unless you intentionally remove the security flag and reintroduce XSS risks. Keep token validation strictly in server components or middleware where the request headers are accessible before rendering

1

u/AlexDjangoX 17d ago

Clerk is your best friend

2

u/[deleted] 22d ago

[removed] — view removed comment

1

u/Neat_Living_6765 21d ago

Thanks for the valuable feedback!!

  1. I created a dal.ts file inside the lib folder. It contains createRemoteJWKSet() to fetch the public key from my backend, and requireRole() internally calls verifySession() to verify the accessToken and check the user's role.

Then I call requireRole() in the page.tsx (Server Components by default) of each protected route, like this:

await requireRole("admin");

return <ProductListPageView />;

2. Yes, I set all the cookie flags: HttpOnly, Secure, and SameSite=Lax.

3. Just to make sure I understand correctly, do you mean I should implement a refresh token that automatically sends the refresh token to the backend to get a new access token before the short-lived access token expires?

4. Yes, both the backend and frontend check authentication and authorization. I don't rely on frontend checks alone.

5. I haven't implemented proxy (middleware) because the docs say it's optional. I also figured it might be redundant... right?

And yes, the generated types already restrict what gets sent to the client.

0

u/[deleted] 21d ago

[removed] — view removed comment

1

u/Neat_Living_6765 21d ago

Yes, the private key remains on the Node.js backend, while the public key is exposed through an API. The frontend fetches and caches the public key using the jose lib.

JWT verification and authorization are performed on both the backend and the frontend, not just on the frontend.

In Next.js, all verification and authorization logic is handled in Server Components, not Client Components.

Thank you for the reminder!! I'm going to implement the CSP headers now!