🌍 NextJS · subject

NextJS Security Best Practices Syllabus

The Security Best Practices syllabus for NextJS in full: 3 chapters and 9 topics, every one listed below, plus 51 Security Best Practices flashcards with answers.

3Chapters
9Topics
51Flashcards

Security Best Practices syllabus: all 3 chapters

Expand any chapter to see its topics and sub-topics.

  1. Authentication and Authorization

    3 topics
    • Using NextAuth.js
    • JWT Tokens
    • Role-Based Access Control
  2. Data Protection

    3 topics
    • Protecting API Routes
    • Handling Sensitive Data
    • Using HTTPS
  3. Vulnerability Management

    3 topics
    • Regular Audits
    • Using Security Headers
    • Dependency Management

NextJS Security Best Practices flashcards — 51 questions with answers

  1. What is NextAuth.js (Auth.js) and what problem does it solve in a Next.js application?

    It is an open-source authentication library for Next.js that handles sign-in flows, sessions, and account linking. It provides built-in support for OAuth providers, email/passwordless login, and credentials, abstracting away token handling, CSRF protection, and session management.

  2. Which two session strategies does NextAuth.js support, and how do they differ?

    The 'jwt' strategy stores session data in an encrypted JWT held in a cookie (stateless, no DB lookup). The 'database' strategy stores sessions in a database and keeps only a session token in the cookie (stateful, revocable server-side).

  3. In NextAuth.js, what is the purpose of the 'jwt' and 'session' callbacks?

    The 'jwt' callback runs whenever a token is created/updated and lets you add custom claims (e.g. role, id) to the token. The 'session' callback shapes the session object returned to the client, letting you expose selected token fields to the frontend.

  4. What environment variable does NextAuth.js require to encrypt/sign tokens and cookies, and why must it be kept secret?

    NEXTAUTH_SECRET (or AUTH_SECRET). It is used to sign/encrypt JWTs and CSRF/session cookies. If leaked, an attacker can forge valid session tokens and impersonate any user.

  5. Where should you place the NextAuth.js configuration route in a Next.js App Router project?

    In app/api/auth/[...nextauth]/route.ts, exporting the handlers (GET and POST) generated from the auth configuration. This catch-all route handles sign-in, callback, sign-out, and session endpoints.

  6. How do you read the current user's session on the server in the Next.js App Router with NextAuth.js?

    By calling the auth() helper (or getServerSession(authOptions)) inside a Server Component, Route Handler, or Server Action, which returns the session object or null if unauthenticated.

  7. What does JWT stand for, and what are its three dot-separated parts?

    JSON Web Token. Its three Base64URL-encoded parts are the Header, the Payload (claims), and the Signature, joined as header.payload.signature.

  8. What information does the header of a JWT typically contain?

    The token type ("typ": "JWT") and the signing algorithm ("alg"), for example HS256 or RS256, used to compute and verify the signature.

  9. Why should you never store sensitive secrets in a JWT payload?

    Because the payload is only Base64URL-encoded, not encrypted, so anyone who possesses the token can decode and read the claims. The signature only guarantees integrity, not confidentiality.

  10. What is the difference between symmetric (HS256) and asymmetric (RS256) JWT signing algorithms?

    HS256 (HMAC-SHA256) uses a single shared secret for both signing and verification. RS256 (RSA-SHA256) uses a private key to sign and a corresponding public key to verify, so verifiers never need the signing secret.

  11. What do the standard JWT claims 'exp', 'iat', and 'nbf' represent?

    'exp' is the expiration time (token invalid after this), 'iat' is the issued-at time, and 'nbf' is the not-before time (token invalid before this). All are NumericDate values in seconds since the Unix epoch.

  12. How is a JWT signature computed for an HMAC-based algorithm like HS256?

    $$\text{signature} = \mathrm{HMACSHA256}\big(\text{base64url}(header) + \texttt{.} + \text{base64url}(payload),\ secret\big)$$

  13. In a JWT-based auth system, what is the purpose of pairing a short-lived access token with a long-lived refresh token?

    The short-lived access token limits the exposure window if it is stolen, while the refresh token (stored more securely and revocable) is used to obtain new access tokens without forcing the user to log in again.

  14. Define Role-Based Access Control (RBAC).

    An authorization model in which permissions are assigned to roles rather than to individual users, and users are granted access by being assigned one or more roles. Access decisions are made by checking whether a user's role holds the required permission.

  15. In RBAC, what are the three core entities and how are they related?

    Users, Roles, and Permissions. Users are assigned Roles (user-role assignment), and Roles are granted Permissions (role-permission assignment); users inherit permissions through their roles.

  16. How does RBAC differ from ABAC (Attribute-Based Access Control)?

    RBAC grants access based on a user's assigned roles. ABAC grants access based on evaluating attributes (of user, resource, action, and environment) against policies, allowing finer-grained, context-aware decisions but with more complexity.

  17. What is the principle of least privilege, and how does RBAC support it?

    It states that every user/process should have only the minimum permissions necessary to perform its function. RBAC supports it by letting administrators define narrow roles and assign users only the roles they need.

  18. In a Next.js app using NextAuth.js, how can you attach a user's role to their session for RBAC checks?

    Add the role to the token in the 'jwt' callback (e.g. token.role = user.role), then expose it in the 'session' callback (e.g. session.user.role = token.role) so it can be checked on the server.

  19. What is the difference between authentication and authorization?

    Authentication verifies WHO a user is (identity, e.g. via login). Authorization determines WHAT an authenticated user is allowed to do (permissions/access). Authentication must precede authorization.

  20. Why should authorization (RBAC) checks be enforced on the server rather than only in the client UI?

    Client-side checks only hide UI elements and can be bypassed by a user calling the API directly or modifying client code. The server is the trust boundary, so it must independently verify every request's permissions.

Show the other 31 Security Best Practices flashcards
  1. In the Next.js App Router, what are the main techniques for protecting an API Route Handler?

    Read the session with auth()/getServerSession at the start of the handler, verify the user is authenticated and authorized (role/permission check), and return a 401 or 403 response early if the check fails before executing any logic.

  2. What is the difference between HTTP status codes 401 and 403 when protecting API routes?

    401 Unauthorized means the request lacks valid authentication credentials (not logged in / invalid token). 403 Forbidden means the user is authenticated but not permitted to access the resource (insufficient privileges).

  3. What role does Next.js Middleware play in protecting routes, and what is one important limitation?

    Middleware runs before a request reaches a route and can redirect or block unauthenticated users centrally. A limitation is that it runs on the Edge runtime and should do lightweight checks; heavy DB-based authorization is better done in the route/handler itself.

  4. Why must every protected API route independently verify authorization even if a page is already gated?

    Because API routes can be called directly (e.g. via fetch/curl) without going through the protected page. Each endpoint is its own entry point and must enforce its own auth checks; page-level protection does not secure the underlying API.

  5. When accepting input in a protected API route, why is input validation still a security requirement?

    Authorization confirms who may call the endpoint, but authenticated users can still send malicious or malformed data. Validating/sanitizing input (e.g. with a schema like Zod) prevents injection, over-posting, and data-integrity attacks.

  6. What is 'sensitive data' in the security context, and give three examples.

    Data that, if disclosed, could harm an individual or organization. Examples: passwords/credentials, personally identifiable information (PII) like SSNs, and financial data such as credit card numbers or API keys/secrets.

  7. Why should passwords be hashed rather than encrypted for storage?

    Hashing is a one-way function, so stored hashes cannot be reversed to reveal the password even if the database is breached, whereas encryption is reversible with the key. Verification is done by hashing the input and comparing hashes.

  8. What is a salt in password hashing, and what attack does it defend against?

    A salt is a unique random value added to each password before hashing. It ensures identical passwords produce different hashes, defeating precomputed rainbow-table attacks and making bulk cracking harder.

  9. Name three password-hashing algorithms designed to be deliberately slow/resource-intensive, and explain why slowness helps.

    bcrypt, scrypt, and Argon2. Their deliberate computational cost (work factor) slows brute-force and dictionary attacks by limiting how many guesses an attacker can compute per second.

  10. In Next.js, why should secrets like database URLs and API keys use environment variables WITHOUT the NEXT_PUBLIC_ prefix?

    Variables prefixed with NEXT_PUBLIC_ are inlined into the client bundle and exposed to the browser. Secrets must omit that prefix so they remain server-only and are never shipped to the client.

  11. What is the difference between encryption at rest and encryption in transit?

    Encryption at rest protects stored data (e.g. database/disk encryption) from attackers who gain storage access. Encryption in transit protects data moving over a network (e.g. via TLS/HTTPS) from interception/eavesdropping.

  12. What is data minimization and why is it a security best practice for handling sensitive data?

    It is the practice of collecting, processing, and retaining only the data strictly necessary for a purpose. Less stored sensitive data means a smaller attack surface and reduced impact if a breach occurs.

  13. What does HTTPS provide over HTTP, in terms of the CIA security properties?

    HTTPS layers TLS over HTTP to provide confidentiality (encryption of traffic), integrity (detection of tampering), and authentication (verifying the server's identity via its certificate).

  14. What protocol underlies HTTPS today, and what replaced the older SSL?

    TLS (Transport Layer Security) underlies HTTPS. TLS replaced the deprecated SSL protocol; modern deployments use TLS 1.2 or TLS 1.3.

  15. During a TLS handshake, how are asymmetric and symmetric cryptography combined?

    Asymmetric cryptography is used to authenticate the server and securely agree on a shared secret (key exchange). That shared secret then keys fast symmetric encryption for the bulk of the session data.

  16. What is the HTTP Strict-Transport-Security (HSTS) header and what does it enforce?

    It is a response header (Strict-Transport-Security) that instructs browsers to only connect to the site over HTTPS for a specified max-age, preventing protocol-downgrade and SSL-stripping man-in-the-middle attacks.

  17. What does a TLS/SSL certificate authority (CA) do, and why does it matter for HTTPS trust?

    A CA is a trusted third party that verifies a domain owner's identity and issues a signed certificate. Browsers trust certificates chaining to a known CA, which is how they confirm they are talking to the genuine server and not an impostor.

  18. What is a security audit in the context of application security?

    A systematic review of an application's code, configuration, dependencies, and infrastructure against security standards to identify vulnerabilities, misconfigurations, and compliance gaps, producing findings and remediation recommendations.

  19. Contrast static application security testing (SAST) with dynamic application security testing (DAST).

    SAST analyzes source code/binaries without executing them to find flaws early (white-box). DAST tests the running application from the outside by sending requests to find runtime vulnerabilities (black-box).

  20. What is penetration testing and how does it differ from a routine vulnerability scan?

    Penetration testing is an authorized simulated attack where testers actively exploit weaknesses to demonstrate real impact. A vulnerability scan merely automatically enumerates known potential weaknesses without exploiting them.

  21. Why are regular (recurring) security audits important rather than a single one-time review?

    Because code, dependencies, threats, and configurations continually change; new vulnerabilities are disclosed over time. Recurring audits catch regressions and newly introduced or newly discovered flaws that a one-time review would miss.

  22. What is the purpose of maintaining audit logs, and what should they capture for security?

    Audit logs create a tamper-evident record of who did what and when, supporting incident detection, forensics, and accountability. They should capture authentication events, authorization decisions, and access to sensitive resources with timestamps and actor identities.

  23. What does the Content-Security-Policy (CSP) header do, and which major attack class does it mitigate?

    CSP restricts which sources the browser may load scripts, styles, images, etc. from. It primarily mitigates cross-site scripting (XSS) by blocking execution of unauthorized/inline scripts.

  24. What is the purpose of the X-Content-Type-Options: nosniff header?

    It tells the browser not to MIME-sniff a response away from its declared Content-Type, preventing attackers from getting content interpreted as an executable script when it was served as another type.

  25. What does the X-Frame-Options (or CSP frame-ancestors) header protect against?

    It controls whether the site can be embedded in an iframe, defending against clickjacking attacks where a malicious site frames your page and tricks users into unintended clicks.

  26. How can you set global security headers in a Next.js application?

    By defining a headers() function in next.config.js that returns header key/value pairs for matching source paths (e.g. adding CSP, HSTS, X-Content-Type-Options), or by setting them in middleware for dynamic responses.

  27. What is Cross-Origin Resource Sharing (CORS) and why should it be configured restrictively?

    CORS is a browser mechanism using response headers (e.g. Access-Control-Allow-Origin) to control which origins may read cross-origin responses. It should be restricted to trusted origins so untrusted sites cannot make authenticated cross-origin requests to your API.

  28. What is a supply-chain attack in the context of dependency management, and give an example vector.

    An attack that compromises software through its third-party dependencies rather than the app's own code. Example vectors: a maintainer publishing a malicious package version, typosquatting a popular package name, or a hijacked/compromised npm account injecting malware.

  29. What does the `npm audit` command do, and what is one of its limitations?

    It scans a project's dependency tree against a vulnerability advisory database and reports known vulnerable packages with severity and fix guidance. A limitation is that it only flags publicly known CVEs/advisories and may produce false positives or miss unreported/zero-day issues.

  30. What is the purpose of a lockfile (e.g. package-lock.json) for dependency security?

    It pins the exact resolved versions and integrity hashes of every dependency, ensuring reproducible installs and preventing unexpected or tampered versions from being silently pulled in across environments.

  31. In semantic versioning (MAJOR.MINOR.PATCH), what do the caret (^) and tilde (~) range specifiers allow, and why does this matter for security?

    The caret (^1.2.3) allows updates that do not change the leftmost non-zero digit (minor and patch). The tilde (~1.2.3) allows only patch updates. This matters because loose ranges can pull in a newly published malicious minor/patch version, so pinning plus a lockfile reduces that risk.

NextJS Security Best Practices FAQ

What is in the NextJS Security Best Practices syllabus?

NextJS Security Best Practices is split into 3 chapters: Authentication and Authorization, Data Protection and Vulnerability Management. Together they contain 9 topics.

How many chapters are in NextJS Security Best Practices?

3 chapters, containing 9 topics. The largest chapter is Authentication and Authorization, with 3 topics.

Are there flashcards for NextJS Security Best Practices?

Yes — a 51-card Security Best Practices deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.