全服务端渲染场景下如何使用Token及JWT认证?
Hey there! Great question—SSR auth can feel like a whole new world when you’re coming from a SPA background, but it’s totally manageable, and JWT works perfectly here. Let’s break down your two main concerns:
How to Add Tokens to Request Headers in SSR
The key difference with SSR is that the initial page load is handled by the server, where you can’t access localStorage (it’s a client-side API). Here’s how to handle both initial and subsequent requests:
1. Initial Server-Side Requests (Page Load/Refresh)
For the first request that triggers SSR, you’ll want to store your token in an HTTP Only Cookie. Browsers automatically attach cookies to every request sent to your domain, so the server can read it directly:
- On the server (e.g., Node.js/Express), you can access the token via
req.cookies.token(you’ll need a middleware likecookie-parser). - Use this token to validate the user, fetch any necessary data, and pass that data to your SSR component for rendering—no need for the client to make an extra API call here.
2. Client-Side Navigation & API Requests
Once the page is rendered and the client takes over (e.g., navigating via a framework’s client-side router), you can fall back to a flow similar to SPAs:
- Extract the token from the cookie (or
localStorage, though cookies are more secure for auth tokens) - Use a request interceptor (with axios, fetch, etc.) to automatically add the token to headers. Example with axios:
// Client-side interceptor axios.interceptors.request.use((config) => { // Extract token from cookie const token = document.cookie.split('; ') .find(row => row.startsWith('token=')) ?.split('=')[1]; if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; });
Can You Use JWT in SSR?
Absolutely—JWT is actually one of the most popular choices for SSR auth. Here’s how it fits in:
- When a user logs in, your server generates a JWT with user claims (like ID, role) and sets it as an HTTP Only, Secure cookie.
- On initial SSR requests, the server reads the JWT from the cookie, verifies its signature and expiration, then parses the user data.
- Pass this parsed user data to your SSR components (e.g., via
getServerSidePropsin Next.js,asyncDatain Nuxt.js) so the component can render personalized content immediately. - For client-side API calls, the JWT is pulled from the cookie and added to headers as shown above.
Key JWT Best Practices for SSR
- Store JWTs in HTTP Only, Secure cookies to prevent XSS attacks (since
localStorageis vulnerable to XSS). - Set a reasonable expiration time for JWTs, and implement a token refresh flow (e.g., server-side checks if the token is near expiration, generates a new one, and updates the cookie).
- Always verify the JWT’s signature on the server before trusting its contents—never rely on client-side validation alone.
Quick Example Flow (Next.js)
- User visits
/dashboard; browser sends the JWT cookie with the request. - In
getServerSideProps, readreq.cookies.token, verify the JWT, fetch user’s dashboard data. - Pass the user data to the Dashboard component, which renders personalized content.
- User clicks a client-side link to
/profile; the client router takes over, and axios automatically adds the JWT to API requests for profile data.
内容的提问来源于Stack Exchange,提问作者Sir Rubberduck

