Questions
29 of 33
1Explain server-side rendering (SSR) in Next.js.
2List the benefits of Server-Side Rendering in Next.js.
3What are server components?
4How to use server components in next js?
5What is the React Server Component Payload (RSC)?
6Describe how server components are rendered.
7Describe server rendering strategies
8How can you keep Server-only Code out of the Client Environment
9What are the issues of using context provider at the root of the application?
10List dynamic functions available to server components.
11List all Dynamic APIs.
12How do we opt for Static Rendering, Dynamic Rendering and Streaming?
13Explain the difference between SSR, SSG, ISR, and CSR in Next.js. When would you choose each?
14How does getServerSideProps work internally? What is its execution context?
15What are the performance trade-offs of SSR vs SSG in a high-traffic production app?
16How does Next.js handle hydration? What is a hydration mismatch, and how do you debug it?
17What happens when getServerSideProps throws an error? How do you handle it gracefully?
18How would you architect a Next.js app that needs both personalised (SSR) and cacheable (SSG) pages at scale?
19Explain the App Router vs Pages Router SSR model differences. How does React Server Components change the SSR paradigm?
20How do React Server Components (RSC) differ from traditional SSR? Can they be used together?
21How does streaming SSR work in Next.js 13+? What role does Suspense play?
22How would you implement partial hydration or Islands Architecture in Next.js?
23Explain how Next.js handles data fetching waterfall problems in SSR and how you'd mitigate them.
24How would you implement partial hydration or Islands Architecture in Next.js?
25How do you implement caching strategies for SSR responses in Next.js? (CDN, Cache-Control, stale-while-revalidate)
26How would you reduce TTFB (Time to First Byte) in an SSR-heavy Next.js app?
27What's the difference between fetch caching in the App Router vs traditional getServerSideProps?
28How do you avoid redundant database/API calls across multiple server components on the same page?
29How do you securely handle authentication in SSR? What are the risks of passing tokens via cookies vs headers?
30How do you prevent sensitive server-side data from leaking to the client bundle?
31How would you implement role-based rendering on the server without exposing protected routes to the client?
32How do you debug SSR-only issues that don't appear in local development?
33How can we control dynamic rendering behaviour in next js?
29 / 33

How do you securely handle authentication in SSR? What are the risks of passing tokens via cookies vs headers?

Securely handle SSR authentication by storing tokens in HTTP-only cookies for automatic server-side transmission, while avoiding header-based tokens that break SSR and localStorage that exposes XSS vulnerabilities

Authentication in Server-Side Rendering (SSR) presents unique challenges because the server needs access to authentication state during the initial page render, before any client-side JavaScript runs. The core requirement is that authentication credentials must be automatically included in HTTP requests made by the server. This fundamental constraint explains why cookie-based authentication dominates SSR architectures: cookies are automatically sent with every HTTP request by the browser, making them accessible in getServerSideProps, middleware, and server components. Header-based authentication (like Authorization: Bearer) fails in SSR because these headers must be manually attached by client-side JavaScript, which hasn't executed during server rendering.

Why Cookies Are Essential for SSR Authentication
  1. 1

    Automatic transmission: Cookies are included in every HTTP request automatically, making them available during server-side rendering without any client-side code execution.

  2. 2

    Middleware compatibility: Cookies can be read in Next.js middleware, enabling authentication checks before pages render and allowing early redirects for unauthenticated users.

  3. 3

    Server Components access: With the App Router, cookies() function provides direct access to cookie values in Server Components, enabling data fetching based on user identity.

  4. 4

    Unified auth model: Cookies work consistently across all Next.js environments: Server Components, Route Handlers, Middleware, API Routes, and SSR.

Header-based authentication breaks SSR because the server cannot access tokens stored in localStorage or sessionStorage during the initial render. When a user visits a protected route like /dashboard directly, the sequence of events reveals the problem: the server renders the page without authentication context, sends unauthenticated HTML, client JavaScript loads, reads the token from storage, and finally fetches protected data—causing UI flickering, extra network requests, and a poor user experience. This is why header-based auth with localStorage is fundamentally incompatible with SSR requirements.

Secure SSR Authentication with HTTP-Only Cookies
Risk Comparison: Cookies vs Headers
  1. 1

    XSS vulnerability: Tokens in localStorage/sessionStorage are accessible to any JavaScript running on your site, making them stealable via XSS attacks. HTTP-only cookies cannot be read by JavaScript, eliminating this risk.

  2. 2

    CSRF protection: Cookies require CSRF protection via SameSite=strict/lax attributes or CSRF tokens. Header-based tokens are naturally immune to CSRF because browsers don't automatically include custom headers in cross-origin requests.

  3. 3

    SSR compatibility: Cookies work automatically with SSR. Headers fail during server rendering because tokens must be manually attached by client JavaScript.

  4. 4

    Token storage security: localStorage is vulnerable to XSS and can be accessed by third-party scripts, browser extensions, and compromised dependencies. HTTP-only cookies remain protected even if malicious scripts execute.

  5. 5

    Request forgery risk: GET requests with cookies can expose user data via CSRF if not properly protected. The official stance is that SSR is secure when GET requests never trigger state-changing operations and CORS headers are correctly configured.

Storing authentication tokens in localStorage creates a severe security risk because any XSS vulnerability—even a minor one from a third-party dependency, an npm package compromise, or an inadvertently exposed console—can lead to token theft. The attacker can then impersonate the user indefinitely. HTTP-only cookies prevent this entirely: the cookie is marked with the HttpOnly flag, meaning the browser's JavaScript engine cannot access it at all. Even if an attacker injects malicious scripts, they cannot read the authentication token. This is why security experts universally recommend HTTP-only cookies for session management in production applications.

While cookies solve XSS and SSR problems, they introduce CSRF (Cross-Site Request Forgery) risks. However, modern browsers provide robust CSRF protection through the SameSite cookie attribute. Setting SameSite=strict or sameSite=lax prevents cookies from being sent with cross-site requests, effectively neutralizing CSRF attacks. For additional protection, many applications implement CSRF tokens or use the double-submit cookie pattern as NextAuth.js does. The OWASP Foundation documents these patterns as secure practices for cookie-based authentication.

Secure Token Transmission with SameSite Protection
When Header-Based Authentication Makes Sense
  1. 1

    Pure API services: Backend-only APIs with no SSR requirements can safely use Authorization headers.

  2. 2

    Mobile applications: Native apps don't use cookies in the same way and typically use Bearer tokens.

  3. 3

    Third-party API access: External consumers of your API expect standard Authorization header patterns.

  4. 4

    SPA-only applications: If your app has no SSR and no plans for it, header-based auth can work, though HTTP-only cookies remain more secure.

For optimal security and user experience, implement the silent refresh pattern: short-lived access tokens (5-15 minutes) stored in HTTP-only cookies, with refresh tokens for obtaining new access tokens. The access token is automatically sent with every request via cookies. When it expires, the server can use the refresh token (also HTTP-only) to issue a new access token transparently. This minimizes the window of compromise if a token is stolen while maintaining seamless UX. The refresh token itself should be rotated and invalidated after use to prevent replay attacks.

Silent Refresh Implementation with Next.js
Security Best Practices Summary
  1. 1

    Always use HTTP-only cookies for session tokens in SSR applications.

  2. 2

    Set Secure flag (HTTPS only), SameSite=strict, and appropriate domain/path restrictions.

  3. 3

    Never store tokens in localStorage or sessionStorage—they are XSS targets.

  4. 4

    Use short-lived access tokens (5-15 minutes) with refresh token rotation.

  5. 5

    Implement proper CORS configuration with credentials: true and origin restrictions.

  6. 6

    Never trust user-controlled headers like X-Forwarded-For or X-HTTP-Method-Override for authentication decisions.

  7. 7

    Validate token signatures properly—never accept unsigned or incorrectly signed tokens.

Difficulty: 6/10
Topics: SSR authentication, cookie vs header security, Next.js session handling

Scenario Questions

0-2 years experience
  1. 1

    In a Next.js page that uses getServerSideProps, how would you read an authentication token from a cookie and make it available to the page component?

  2. 2

    If you set an HttpOnly cookie containing a JWT, what happens when the client tries to fetch data from an API route using fetch without including credentials?

  3. 3

    What flag would you add to a Set-Cookie header to protect the token from being accessed by JavaScript, and why is that important for SSR?

2-5 years experience
  1. 1

    You notice that after deploying a new version, SSR pages are rendering as unauthenticated even though the token cookie is present. Walk me through how you'd debug the issue.

  2. 2

    Explain the trade‑offs between sending the JWT in an Authorization header versus storing it in an HttpOnly cookie when using Next.js API routes with SSR.

  3. 3

    Suppose you need to support both server‑side rendering and client‑side navigation in the same app. How would you ensure the auth token is sent correctly in both contexts without exposing it to XSS?

5-8 years experience
  1. 1

    Design a secure authentication flow for a Next.js app that uses SSR for protected pages, supports token refresh, and works across multiple subdomains. What components would you build and why?

  2. 2

    What are the security implications of using SameSite=Strict vs SameSite=Lax for auth cookies in an SSR context, and how would you mitigate CSRF attacks?

  3. 3

    If you had to migrate an existing Next.js codebase from header‑based token passing to HttpOnly cookies, what steps would you take to minimize downtime and avoid breaking existing sessions?

8+ years experience
  1. 1

    At a company‑wide level, how would you define a strategy for handling authentication across all Next.js services, balancing security, developer experience, and performance?

  2. 2

    Discuss how you would evaluate the long‑term maintainability of using cookies versus headers for auth in a micro‑frontend architecture that shares authentication state.

  3. 3

    Imagine a future requirement to support third‑party identity providers (OAuth, SAML) in the same SSR app. How would you extend the current token handling design to accommodate them while preserving security guarantees?

Follow-up Questions

  • Can you elaborate on how you’d protect against CSRF in that design?
  • What would you monitor in production to detect token‑related issues?
  • How does your approach change if the app must support mobile browsers with limited cookie support?