Skip to content

Cognizant MERN Stack Interview Questions & Answers

Curated interview practice questions with answers. These are practice scenarios, not a verified list of past interview questions.

About Cognizant hiring for MERN Stack roles

Cognizant is a US-headquartered IT services and consulting company with most of its workforce based in India. It provides application development, testing, cloud, digital engineering and data analytics services, with strong practices in healthcare, insurance and banking. In India it hires for programmer analyst, quality engineer and data roles through campus and off-campus programmes such as GenC.

For MERN Stack roles, this Cognizant practice set focuses most on Testing, Deployment and DevOps (6), Express.js and REST APIs (6), Modern JavaScript (ES6+) (4), Authentication and Security (4). It has 11 easy, 18 medium, 1 hard questions, so you can start easy and work up to the harder ones.

Company type
IT services
Headquarters
Teaneck, New Jersey, USA
Main India offices
Chennai, Bengaluru, Pune, Hyderabad, Kolkata

Cognizant MERN Stack interview process

  1. Online assessment (aptitude + reasoning)
  2. Coding assessment
  3. Technical interview
  4. HR round

Typical pattern based on public candidate experiences. Rounds vary by role, team and year.

Solved for CognizantStart 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

Explain destructuring, the spread operator and rest parameters.

Save to ▾
Show answer
Destructuring unpacks values from arrays or objects into variables, for example const { name, email } = user, with optional defaults and renaming. Spread (...) expands an iterable or object, used to copy arrays, merge objects or pass arguments. Rest uses the same syntax to collect remaining items, as in function sum(...nums) or const { password, ...safeUser } = user. In React, spread is used constantly to create new state objects immutably.
02

After deploying a React app, refreshing on a page like /dashboard shows a 404 error. Why, and how do you fix it?

Save to ▾
Show answer
With client-side routing, /dashboard exists only inside React Router, not as a file on the server. When the browser requests it directly, the web server finds no file and returns 404. Configure the server to fall back to index.html for unknown paths: try_files $uri /index.html in Nginx, a rewrite rule on static hosts, or a catch-all route in Express that serves index.html after the API routes.
03

How do you add a timeout to a fetch call in Node.js?

Save to ▾
Show answer
Node 18 and later ship a global fetch. Use AbortSignal.timeout to cancel slow requests. async function getJSON(url) { try { const res = await fetch(url, { signal: AbortSignal.timeout(5000) }); if (!res.ok) throw new Error(`HTTP ${res.status}`); return await res.json(); } catch (err) { if (err.name === 'TimeoutError') console.error('Request timed out'); throw err; } } Without a timeout, a hung upstream can hold connections open indefinitely.
04

What is Express.js and what is middleware?

Save to ▾
Show answer
Express is a minimal web framework for Node.js that adds routing, middleware and helpers on top of the http module. Middleware is a function with the signature (req, res, next) that runs during the request cycle. It can read or modify the request, end the response, or call next() to pass control on. Body parsing, logging, authentication, CORS and error handling are all built as middleware.
05

What are streams in Node.js and what types exist?

Save to ▾
Show answer
Streams process data in chunks instead of loading it all into memory. The four types are Readable (file read, HTTP request), Writable (file write, HTTP response), Duplex (TCP socket) and Transform (gzip, encryption), which modifies data as it passes. Streams handle backpressure, pausing the source when the destination is slow. pipeline() from node:stream/promises connects them safely and handles errors and cleanup.
06

How does the JavaScript event loop work with microtasks and macrotasks?

Save to ▾
Show answer
JavaScript runs one call stack. When the stack is empty, the event loop first drains the entire microtask queue, which holds Promise callbacks, queueMicrotask and await continuations. Only then does it pick the next macrotask, such as a setTimeout callback, an I/O callback or a UI event. This is why a resolved Promise callback always runs before a setTimeout of 0 ms scheduled at the same time.
07

What does the helmet middleware do in Express?

Save to ▾
Show answer
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.
08

Why are functional components preferred over class components today?

Save to ▾
Show answer
Functional components with hooks need less code, avoid confusion around this binding, and let you reuse stateful logic through custom hooks instead of higher-order components or render props. All new React features, such as Server Components and hooks like useActionState, target functions. Class components still work and appear in older codebases, and error boundaries still require a class or a library wrapper.
09

Attackers are trying thousands of passwords on your login endpoint. How do you defend it?

Save to ▾
Show answer
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.
10

Tell me about a time you disagreed with a teammate about an API design decision.

Save to ▾
Show answer
Situation: a frontend teammate wanted one endpoint returning the entire dashboard, while I preferred separate resource endpoints. Task: we needed a decision before sprint planning. Action: I listed trade-offs, measured payload size and call counts for both, and we agreed on resource endpoints plus one aggregated summary endpoint for the first screen. Result: the dashboard loaded faster and the API stayed reusable for the mobile app.
11

What is a custom hook and what rules must hooks follow?

Save to ▾
Show answer
A custom hook is a function whose name starts with use and that calls other hooks to package reusable stateful logic, such as useFetch, useDebounce or useAuth. Each component using it gets its own state. Hooks must be called at the top level of a component or another hook, never inside conditions, loops or nested functions, so React can match state by call order. The eslint-plugin-react-hooks rules enforce this.
12

Why does the order of middleware matter in Express?

Save to ▾
Show answer
Express runs middleware and routes in the order they are registered. If express.json() is added after your routes, req.body will be undefined. Authentication middleware must come before protected routes, static file serving usually comes early, a 404 handler comes after all routes, and the error-handling middleware must be registered last. If a middleware neither sends a response nor calls next(), the request hangs.
13

What are the important changes in Express 5 compared to Express 4?

Save to ▾
Show answer
Express 5 requires a modern Node version and forwards rejected Promises from async handlers to error middleware. Route path syntax moved to a newer path-to-regexp, so wildcards must be named, like /*splat, and regex-style characters in strings are no longer supported. Deprecated methods like res.send(status, body) were removed, req.query is read-only, and req.body is undefined unless a body parser runs.
14

Group an array of order objects by their status using reduce.

Save to ▾
Show answer
reduce builds an object whose keys are statuses and values are arrays. const grouped = orders.reduce((acc, order) => { (acc[order.status] ||= []).push(order); return acc; }, {}); // { paid: [...], pending: [...] } Newer runtimes also offer Object.groupBy(orders, (o) => o.status), which returns the same shape with a null prototype.
15

How do environment variables work in a Vite React app compared to a Node.js backend?

Save to ▾
Show answer
In Node, process.env is read at runtime on the server, so secrets are safe there. In a Vite app, only variables prefixed with VITE_ are exposed, through import.meta.env, and they are embedded into the JavaScript bundle at build time. Anything in the frontend bundle is public, so never put database passwords or secret keys there. Changing a frontend variable requires a rebuild.
16

Create an AuthContext with a provider and a custom hook.

Save to ▾
Show answer
A provider plus a safe hook: const AuthContext = createContext(null); export function AuthProvider({ children }) { const [user, setUser] = useState(null); const login = async (creds) => { const res = await api.post('/auth/login', creds); setUser(res.data.user); }; const logout = () => setUser(null); const value = useMemo(() => ({ user, login, logout }), [user]); return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>; } export function useAuth() { const ctx = useContext(AuthContext); if (!ctx) throw new Error('useAuth must be used inside AuthProvider'); return ctx; }
17

Walk me through a MERN project you built, end to end.

Save to ▾
Show answer
Situation: I built a job portal as my major project. Task: let recruiters post jobs and students apply with resumes. Action: I designed MongoDB collections for users, jobs and applications with indexes, built an Express REST API with JWT auth and role checks, a React frontend with React Router and TanStack Query, uploaded resumes to cloud storage, wrote API tests and deployed with Docker. Result: 60 classmates used it during placement season.
18

How do you implement code splitting in a React app?

Save to ▾
Show answer
Use dynamic import with React.lazy, for example const Admin = lazy(() => import('./Admin')), and wrap it in a Suspense boundary with a fallback. Bundlers like Vite then create a separate chunk that loads only when needed. Split by route first, then by heavy components like charts, editors and maps. Preload likely next routes on hover, and check results with a bundle analyser such as rollup-plugin-visualizer.
19

How does error-handling middleware work in Express, and what changed in Express 5?

Save to ▾
Show answer
Error handlers have four parameters, (err, req, res, next), and Express routes errors to them when you call next(err) or throw synchronously. In Express 4, rejected Promises in async handlers were not caught, so you needed try/catch or a wrapper. Express 5 automatically forwards rejected Promises from async handlers to the error middleware. Register the error handler after all routes and avoid leaking stack traces in production.
20

What is the aggregation pipeline and what are its common stages?

Save to ▾
Show answer
The aggregation pipeline processes documents through a sequence of stages, each transforming the stream. Common stages are $match to filter, $group to aggregate with operators like $sum and $avg, $project or $addFields to shape fields, $sort, $limit, $skip, $lookup to join another collection, $unwind to flatten arrays and $facet for multiple outputs. Put $match and $sort early so they can use indexes and reduce the data volume.
21

What is a Buffer in Node.js?

Save to ▾
Show answer
A Buffer is a fixed-size chunk of raw binary memory allocated outside the V8 heap, used for files, network packets, images and encodings. You create one with Buffer.from('hello') or Buffer.alloc(10) and convert with toString('utf8'), toString('base64') or toString('hex'). Streams deliver data as Buffers by default. Buffer.allocUnsafe is faster but may contain old memory, so it must be filled before use.
22

How does Supertest help test Express APIs?

Save to ▾
Show answer
Supertest sends HTTP requests directly to your Express app object without starting a real server on a port, and lets you assert on status codes, headers and bodies. This is why you export the app separately from the server.listen call. Combine it with an in-memory MongoDB using mongodb-memory-server or a dedicated test database, seeding data before each test and clearing it afterwards.
23

What is PM2 and why is it used to run Node.js in production?

Save to ▾
Show answer
PM2 is a process manager for Node.js. It keeps the app alive by restarting it after crashes, runs multiple instances in cluster mode to use all CPU cores, supports zero-downtime reloads with pm2 reload, manages logs and starts apps on server boot. Configuration lives in an ecosystem.config.js file. On container platforms like Kubernetes, the orchestrator often replaces PM2's restart and scaling role.
24

How does routing work in a React single-page app using React Router?

Save to ▾
Show answer
React Router maps URL paths to components without full page reloads. You define routes, often with createBrowserRouter or Routes and Route elements, including nested routes that render inside a parent layout through Outlet. Link and NavLink change the URL, useNavigate navigates in code, and useParams reads dynamic segments like /products/:id. Recent versions also provide loaders and actions for data fetching and form submission.
25

What is mocking and when should you mock in tests?

Save to ▾
Show answer
Mocking replaces a real dependency with a controlled fake so tests are fast, isolated and deterministic. Mock things you do not own or that are slow or unpredictable: payment gateways, email services, third-party APIs, time and random values. In React tests, Mock Service Worker intercepts network requests. Avoid mocking everything, especially your own database layer in integration tests, or tests will pass while real code fails.
26

How should passwords be stored, and why use bcrypt?

Save to ▾
Show answer
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.
27

What is CORS and how do you configure it in an Express API?

Save to ▾
Show answer
CORS is a browser security mechanism that blocks a page from reading responses from a different origin unless the server allows it through headers like Access-Control-Allow-Origin. For non-simple requests the browser sends a preflight OPTIONS request first. In Express, use the cors package with an explicit allowlist, for example cors({ origin: ['https://app.example.com'], credentials: true }), instead of allowing every origin with credentials.
28

Write an Express middleware that verifies a JWT from the Authorization header.

Save to ▾
Show answer
Reject missing or invalid tokens with 401. import jwt from 'jsonwebtoken'; export function requireAuth(req, res, next) { const header = req.headers.authorization || ''; const token = header.startsWith('Bearer ') ? header.slice(7) : null; if (!token) return res.status(401).json({ message: 'Token missing' }); try { req.user = jwt.verify(token, process.env.JWT_SECRET); next(); } catch { res.status(401).json({ message: 'Invalid or expired token' }); } } router.get('/me', requireAuth, getProfile);
29

Explain indexes in MongoDB, compound indexes and the ESR rule.

Save to ▾
Show answer
An index is a sorted structure that lets queries avoid scanning every document. A compound index covers multiple fields in order, like { userId: 1, createdAt: -1 }, and supports queries on its leading prefix. The ESR guideline says order fields as Equality first, then Sort, then Range. Indexes speed reads but slow writes and use memory, so create them for real query patterns and drop unused ones.
30

What is a closure and where is it useful?

Save to ▾
Show answer
A closure is a function that remembers the variables of the scope where it was created, even after that outer function has returned. For example, a makeCounter function can return an inner function that increments a private count variable. Closures power data privacy, function factories, memoization, debounce and throttle helpers, and React hooks, where event handlers capture props and state from the render that created them.

Tips to crack the Cognizant MERN Stack interview

  • Understand the GenC, GenC Next and GenC Elevate tracks so you know which skills and coding level each role expects.
  • Revise SQL queries, OOP concepts and basic testing terminology since many freshers are placed in development or QA projects.
  • Read about Cognizant's healthcare and life sciences domain work, which is a large part of its client base.
  • Keep a one-minute story ready for every project on your CV: problem, your part, tools, result.
  • Practise the hard questions on this page aloud; Cognizant interviewers usually ask follow-ups on your first answer.

Frequently asked questions

How many rounds are there in the Cognizant MERN Stack interview?

Candidates usually go through 4 stages: Online assessment (aptitude + reasoning); Coding assessment; Technical interview; HR round. The exact rounds change with the role, team, location and your experience, so confirm the process with the recruiter.

Which topics should I prepare for the Cognizant MERN Stack interview?

This practice set leans on Testing, Deployment and DevOps (6), Express.js and REST APIs (6), Modern JavaScript (ES6+) (4), Authentication and Security (4). Revise those first, then practise explaining one or two of your own projects end to end, because most Cognizant interviewers ask you to walk through real work.

Are these the exact questions asked at Cognizant?

No. These are curated practice questions that match the skills and difficulty usually tested in it services interviews like Cognizant's. They are not a leaked or verified list of past questions.

Where does Cognizant hire MERN Stack professionals in India?

Cognizant has large teams in Chennai, Bengaluru, Pune, Hyderabad, Kolkata. Openings and locations change often, so check the Cognizant careers page and filter by city and experience.

MERN Stack questions for similar companies