Publicis Sapient MERN Stack Interview Questions & Answers
Curated interview practice questions with answers. These are practice scenarios, not a verified list of past interview questions.
About Publicis Sapient hiring for MERN Stack roles
Publicis Sapient is the digital business transformation arm of Publicis Groupe, combining strategy, product, experience design, engineering and data. Its India offices in Gurugram, Noida and Bengaluru deliver engineering and data work for global clients in retail, financial services and energy. It hires for software engineers, quality engineers, data engineers and data scientists.
For MERN Stack roles, this Publicis Sapient practice set focuses most on Authentication and Security (6), React Fundamentals (5), React Hooks, State and Performance (4), MongoDB and Mongoose (4). It has 6 easy, 22 medium, 2 hard questions, so you can start easy and work up to the harder ones.
Company type
Consulting
Headquarters
Boston, Massachusetts, USA
Main India offices
Gurugram, Noida, Bengaluru
Publicis Sapient MERN Stack interview process
Online coding assessment
Technical round 1 (coding + fundamentals)
Technical round 2 (design or domain)
Managerial round
HR round
Typical pattern based on public candidate experiences. Rounds vary by role, team and year.
Solved for Publicis SapientStart 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
How does the useEffect dependency array work and why is cleanup important?
useEffect runs after render. With no array it runs after every render, with an empty array only after mount, and with dependencies whenever any of them change by Object.is comparison. The function you return is the cleanup, which runs before the next effect and on unmount. Use it to remove listeners, clear intervals, abort requests and close sockets, otherwise you get leaks and duplicate subscriptions.
02
You are building a registration form with ten fields and validation. How do you manage its state?
For a simple form, keep a single state object and update fields with a shared handler using the input name, for example setForm({ ...form, [e.target.name]: e.target.value }). Validate on blur and submit, storing errors in another object. For larger forms, use React Hook Form with a zod schema, which reduces re-renders and shares the validation schema with the Express backend.
03
A MongoDB query on an orders collection takes 3 seconds. How do you diagnose and fix it?
Run the query with .explain('executionStats') and check whether the winning plan is COLLSCAN and how totalDocsExamined compares to nReturned. Create an index matching the filter and sort, following ESR, and confirm it becomes IXSCAN. Also project only needed fields, add limits, use lean in Mongoose, and check the profiler or Atlas Performance Advisor for other slow queries. Re-test with production-like data volume.
04
How would you explain a technical decision, such as choosing REST over GraphQL, to a non-technical manager?
Situation: my manager asked why we were not using GraphQL like a competitor. Task: explain without jargon. Action: I compared it to ordering from a fixed menu versus a custom kitchen, explained that our screens need simple, predictable data, and that REST meant faster delivery with our team's current skills, lower risk and easier caching. Result: the manager approved the plan and we revisited the idea later.
05
What is the difference between unit, integration and end-to-end tests in a MERN app?
Unit tests check a single function or component in isolation, such as a price calculator or a button, and are fast. Integration tests check pieces working together, such as an Express route with a real test database using Supertest. End-to-end tests drive the full app in a real browser with Playwright or Cypress, for example signup to checkout. Keep many unit tests, fewer integration tests and a small set of critical E2E flows.
06
A search box fires an API request on every keystroke and overloads the backend. How would you solve it?
Debounce the input so the request goes out only after the user stops typing for around 300 ms. Also skip very short queries, cancel the previous request with AbortController so stale responses cannot overwrite newer ones, and cache recent results. On the server side, add rate limiting and an index on the searched field. Throttling is the alternative when you need periodic updates, like scroll tracking.
07
Duplicate user accounts with the same email are being created even though the code checks for an existing email first. Why, and how do you fix it?
Check-then-insert is a race condition: two concurrent requests both see no user and both insert. The real fix is a unique index on email, normalised to lowercase, so the database rejects the second insert with error code 11000. Catch that error and return 409 Conflict. Clean up existing duplicates before building the index, otherwise index creation fails.
Debounce delays a call until a quiet period has passed. Each new call clears the previous timer.
function debounce(fn, delay = 300) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const onSearch = debounce((q) => fetchResults(q), 400);
It relies on a closure over timer and keeps this and arguments intact.
09
How do you implement code splitting in a React app?
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.
10
How do you add a timeout to a fetch call in Node.js?
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.
It must keep result order and reject on the first failure.
function promiseAll(items) {
return new Promise((resolve, reject) => {
const results = [];
let done = 0;
if (items.length === 0) return resolve(results);
items.forEach((item, i) => {
Promise.resolve(item).then((value) => {
results[i] = value;
done += 1;
if (done === items.length) resolve(results);
}, reject);
});
});
}
Promise.resolve handles plain values mixed with Promises.
12
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.
13
How would you structure the folders of a production Express API?
A layered structure keeps responsibilities clear: src/routes for route definitions, src/controllers for request and response handling, src/services for business logic, src/models for Mongoose schemas, src/middlewares for auth, validation and errors, src/config for environment and database setup, src/utils for helpers, and tests alongside or in a tests folder. Keep app.js, which builds the app, separate from server.js, which listens, so tests can import the app.
14
Describe a mistake you made with data and how you handled it.
Situation: I ran an update script against the staging database with a wrong filter and modified thousands of records. Task: restore data before QA testing next morning. Action: I informed my lead immediately, restored from the nightly backup, re-applied the day's valid changes, and then added a dry-run mode and a count confirmation step to our scripts. Result: QA was not blocked, and no similar incident happened again.
15
Set up React Router with a layout, a list page and a detail page using useParams.
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.
18
What is the difference between props and state in React?
Props are inputs passed from a parent to a child component; they are read-only inside the child. State is data owned and managed by a component itself, created with useState or useReducer, and changing it triggers a re-render. A common pattern is that a parent keeps state and passes both the value and a setter function down as props to children.
19
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.
20
How do you implement graceful shutdown for a Node.js API during deployments?
Listen for SIGTERM and SIGINT. When received, stop accepting new connections with server.close(), let in-flight requests finish, close database connections with mongoose.connection.close() and other resources, then exit with code 0. Set a timeout, for example 10 seconds, after which you force exit. In Kubernetes or behind a load balancer, also fail the readiness check first so traffic stops reaching the instance.
21
Two sibling components need to share data. How do you handle it?
Lift the shared state to their nearest common parent and pass the value to one sibling and an updater to the other. If the data is needed by many components deep in the tree, use Context or a state library like Zustand or Redux Toolkit. If the data comes from the server, a data-fetching library like TanStack Query can share the cached result across components.
22
Write Express middleware that logs method, URL, status code and response time.
Hook into the response finish event to know the final status.
function requestLogger(req, res, next) {
const start = process.hrtime.bigint();
res.on('finish', () => {
const ms = Number(process.hrtime.bigint() - start) / 1e6;
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${ms.toFixed(1)}ms`);
});
next();
}
app.use(requestLogger);
In production, use a structured logger like pino instead of console.log.
23
A component calls setState inside useEffect and the app goes into an infinite render loop. Why?
The effect updates state, which re-renders, which runs the effect again. This happens when the dependency array is missing, or when a dependency is a new object or array created every render, or when the effect sets the same state it depends on. Add correct dependencies, move object creation inside the effect or memoize it, and ask whether the value can be calculated during render instead.
24
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.
Redux keeps global state in a single store that changes only through dispatched actions handled by reducers. Redux Toolkit is the official modern way to write Redux: configureStore sets up the store with DevTools, createSlice generates actions and reducers and lets you write mutating code safely using Immer, and createAsyncThunk handles async requests. RTK Query adds data fetching and caching. Components use useSelector and useDispatch.
26
Write a useDebounce hook and use it for a search input.
req.params holds named route segments, so for /users/:id a request to /users/42 gives req.params.id equal to '42'. req.query holds the query string, so ?page=2&sort=name gives { page: '2', sort: 'name' }. req.body holds the parsed request payload, available only after a parser like express.json(). Params and query values are strings, so convert and validate them before use.
28
How does the JavaScript event loop work with microtasks and macrotasks?
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.
29
You need to rename a field and change its type across 20 million documents in production. How do you do it safely?
Avoid a single big blocking update. Make the application read both old and new formats first, then run a batched migration script that processes documents in chunks by _id range with bulkWrite, throttled and resumable, or an updateMany with an aggregation pipeline during low traffic. Track progress, verify counts, back up first, then remove the old-field handling in a later release.
30
Write a role-based authorization middleware for Express.
A small factory function keeps routes readable.
export const authorize = (...roles) => (req, res, next) => {
if (!req.user) return res.status(401).json({ message: 'Login required' });
if (!roles.includes(req.user.role)) {
return res.status(403).json({ message: 'Forbidden' });
}
next();
};
router.delete('/products/:id', requireAuth, authorize('admin'), deleteProduct);
router.patch('/articles/:id', requireAuth, authorize('admin', 'editor'), updateArticle);
It must run after the authentication middleware that sets req.user.
Tips to crack the Publicis Sapient MERN Stack interview
Revise Java or JavaScript fundamentals, microservices and REST APIs, which are common in Publicis Sapient engineering roles.
Prepare to discuss design patterns and clean code, as technical rounds often go beyond simple coding.
Read about its SPEED model of strategy, product, experience, engineering and data for culture questions.
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; Publicis Sapient interviewers usually ask follow-ups on your first answer.
Frequently asked questions
How many rounds are there in the Publicis Sapient MERN Stack interview?
Candidates usually go through 5 stages: Online coding assessment; Technical round 1 (coding + fundamentals); Technical round 2 (design or domain); Managerial round; 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 Publicis Sapient MERN Stack interview?
This practice set leans on Authentication and Security (6), React Fundamentals (5), React Hooks, State and Performance (4), MongoDB and Mongoose (4). Revise those first, then practise explaining one or two of your own projects end to end, because most Publicis Sapient interviewers ask you to walk through real work.
Are these the exact questions asked at Publicis Sapient?
No. These are curated practice questions that match the skills and difficulty usually tested in consulting interviews like Publicis Sapient's. They are not a leaked or verified list of past questions.
Where does Publicis Sapient hire MERN Stack professionals in India?
Publicis Sapient has large teams in Gurugram, Noida, Bengaluru. Openings and locations change often, so check the Publicis Sapient careers page and filter by city and experience.