Authentication and Security Interview Questions for MERN Stack
25 Authentication and Security questions with answers for mern stack roles — 5 easy, 13 medium, 7 hard.
About Authentication and Security
Every MERN app needs secure login and data protection. This topic covers authentication versus authorization, JWTs, sessions, refresh tokens, cookie security, password hashing with bcrypt, OAuth and Google login, role-based access, and defences against XSS, CSRF, NoSQL injection and brute-force attacks. Interviewers expect you to explain trade-offs and write auth middleware confidently.
Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
What is the difference between authentication and authorization?
Authentication verifies who the user is, for example by checking email and password, an OTP or a Google login, and results in a session or token. Authorization decides what that authenticated user may do, such as whether a normal user can delete products or only an admin can. Failed authentication should return 401 Unauthorized, while an authenticated user lacking permission should get 403 Forbidden.
A JSON Web Token is a compact, URL-safe token made of three Base64URL-encoded parts separated by dots: the header with algorithm and type, the payload with claims like sub, role and exp, and the signature created from the header and payload using a secret or private key. The signature proves the token was not altered, but the payload is readable by anyone, so never put passwords or sensitive data in it.
03
How should passwords be stored, and why use bcrypt?
Never store plain or reversibly encrypted passwords. Store a slow, salted hash. bcrypt generates a random salt per password, so identical passwords produce different hashes and rainbow tables fail, and its cost factor, typically 10 to 12, makes brute force expensive. At login use bcrypt.compare. Argon2id is a modern alternative. Fast hashes like MD5 or SHA-256 alone are unsuitable for passwords.
helmet sets HTTP security headers in one line: Content-Security-Policy to restrict script sources, Strict-Transport-Security to force HTTPS, X-Content-Type-Options nosniff, X-Frame-Options or frame-ancestors to prevent clickjacking, and Referrer-Policy. It also removes the X-Powered-By header that reveals Express. It is not a complete security solution, but it is a cheap, standard first layer in every production API.
05
Write a register endpoint that hashes the password with bcrypt.
The access token is short-lived, for example 15 minutes, and is sent with every API request, so if stolen it is useful only briefly. The refresh token is long-lived, stored more securely in an httpOnly cookie, and is used only at a refresh endpoint to get new access tokens. Refresh tokens should be stored server-side or hashed so they can be revoked, and rotated on every use to detect theft.
07
Should you store a JWT in localStorage or in an httpOnly cookie?
localStorage is readable by any JavaScript on the page, so an XSS bug can steal the token. An httpOnly, Secure cookie cannot be read by JavaScript, which protects against token theft through XSS, but cookies are sent automatically, so you must defend against CSRF with SameSite=Lax or Strict and CSRF tokens where needed. A common pattern keeps the refresh token in an httpOnly cookie and the access token in memory.
08
How does React protect against XSS and where can XSS still happen?
React escapes values rendered in JSX, so user text containing script tags is shown as text, not executed. XSS can still happen through dangerouslySetInnerHTML with unsanitised HTML, javascript: URLs in href attributes, injecting user data into script tags during SSR, or unsafe third-party scripts. Sanitise any HTML with DOMPurify, validate URLs, set a Content Security Policy, and keep tokens out of JavaScript-readable storage.
09
What is NoSQL injection and how do you prevent it in a MongoDB app?
NoSQL injection happens when user input is placed directly into a query and contains operators. For example, a login body of { email: 'a@b.com', password: { $ne: null } } could match any password if passed straight to findOne. Prevent it by validating types with zod or Joi, casting inputs to strings, stripping keys starting with $ or containing dots, enabling Mongoose strictQuery, and never building $where queries from user input.
10
Your app needs user, editor and admin roles with different permissions. How would you implement it?
Store a role, or a list of permissions, on the user document and include it in the token or load it in the auth middleware. Write an authorize middleware that checks allowed roles or permissions per route, for example authorize('admin'). Add ownership checks in services, such as an editor editing only their own articles. In React, hide buttons by role for user experience, but always enforce rules on the server.
11
A developer accidentally pushed the .env file with the MongoDB password and JWT secret to a public repository. What do you do?
Treat the secrets as compromised immediately. Rotate the MongoDB user password, the JWT secret and any API keys; rotating the JWT secret logs everyone out, which is acceptable. Check database and cloud logs for suspicious access. Remove the file, add .env to .gitignore, and purge it from history with a tool like git filter-repo, though rotation matters more. Enable secret scanning and pre-commit hooks to prevent repeats.
12
Attackers are trying thousands of passwords on your login endpoint. How do you defend it?
Apply strict rate limits on login per IP and per account using a shared Redis store, add progressive delays or temporary account lockout after several failures, and show a CAPTCHA after repeated attempts. Return a generic error message so attackers cannot tell whether an email exists. Log and alert on spikes, check for breached passwords at signup, and offer two-factor authentication for sensitive accounts.
13
Design a secure forgot-password flow for a MERN application.
The user submits an email; always respond with the same message whether or not it exists. Generate a random token with crypto.randomBytes, store only its hash with an expiry of around 15 minutes, and email a link with the raw token. On submission, hash the token, find a matching unexpired record, set the new hashed password, delete the token and invalidate existing sessions. Rate limit the endpoint.
14
Write an Express middleware that verifies a JWT from the Authorization header.
Validate every request body, params and query against a schema with zod or Joi, rejecting unknown fields and wrong types. Apply body size limits with express.json({ limit: '100kb' }). Strip MongoDB operator keys from input with a small sanitising middleware or library, and keep Mongoose strict mode on. Escape or sanitise HTML with DOMPurify before storing rich text, and validate ObjectIds before querying.
18
Tell me about a time you found and fixed a security issue in an application.
Situation: while testing an order history feature, I noticed changing the order id in the URL showed another user's order. Task: fix this insecure direct object reference before release. Action: I added an ownership check in the service layer so queries always filter by the logged-in user's id, wrote tests for cross-user access, and reviewed similar endpoints. Result: we fixed four endpoints and added ownership checks to our review checklist.
19
Compare session-based authentication with JWT-based authentication.
With sessions, the server stores session data in a store such as Redis and the browser holds only a session id cookie; revoking is easy, but every request needs a lookup. With JWTs, the token itself carries signed claims, so servers can verify it without a lookup, which suits microservices and mobile clients. JWTs are harder to revoke before expiry, so keep them short-lived and pair them with refresh tokens.
20
What is CSRF and how do SameSite cookies help prevent it?
Cross-site request forgery tricks a logged-in user's browser into sending a request to your site from a malicious page, and the browser attaches the user's cookies automatically. SameSite=Lax blocks cookies on cross-site POST requests and SameSite=Strict blocks them on all cross-site requests, which stops most CSRF. For extra safety use CSRF tokens on state-changing routes, never change state with GET, and verify the Origin header.
21
How does Sign in with Google work using OAuth 2.0 and OpenID Connect?
The app redirects the user to Google's authorization endpoint with client id, redirect URI, scopes like openid email and a state value. After consent, Google redirects back with an authorization code, and the backend exchanges it for an ID token and access token. With OpenID Connect, the ID token is a signed JWT whose signature, audience and expiry you verify, then you create your own session. PKCE protects the code exchange.
22
When a user logs out or changes password, how do you make sure their existing JWTs stop working?
Stateless JWTs stay valid until expiry, so keep access tokens short-lived and revoke refresh tokens by deleting or flagging them in the database. For immediate invalidation, store a tokenVersion or passwordChangedAt on the user and include it in the token; the auth middleware rejects tokens with an older version. Alternatively keep a Redis denylist of token ids until they expire. Clear the refresh cookie on logout.
23
Users can upload profile pictures and documents. What security measures do you put in place?
Enforce size limits and an allowlist of types, checking magic bytes rather than trusting the extension or Content-Type. Rename files with random ids, store them in object storage outside the web root, and serve them from a separate domain or with Content-Disposition attachment for documents. Strip image metadata, scan for malware where needed, use pre-signed URLs with expiry for private files, and never execute or include uploaded files.
24
Write an Axios interceptor in React that refreshes the access token on a 401 response.
Situation: a product manager wanted a file-sharing feature live by Friday, but uploads had no type or access checks. Task: protect users without blocking the launch. Action: I explained the risk in business terms, proposed shipping with private pre-signed links and type limits first, and deferring sharing features to the next sprint. Result: we launched on time with the risky part removed, and the full feature followed a week later.
Frequently asked questions
How important is Authentication and Security in MERN Stack interviews?
Every MERN app needs secure login and data protection. This topic covers authentication versus authorization, JWTs, sessions, refresh tokens, cookie security, password hashing with bcrypt, OAuth and Google login, role-based access, and defences against XSS, CSRF, NoSQL injection and brute-force attacks. Interviewers expect you to explain trade-offs and write auth middleware confidently.
How should I use the Authentication and Security sheet?
Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.