Skip to content

Nagarro MERN Stack Interview Questions & Answers

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

About Nagarro hiring for MERN Stack roles

Nagarro is a digital engineering and technology consulting company with a large workforce in India. It works on custom software, digital product engineering, testing, cloud and data projects for clients in Europe, North America and other regions. In India it hires for software engineers, test engineers and data professionals.

For MERN Stack roles, this Nagarro practice set focuses most on Express.js and REST APIs (7), MongoDB and Mongoose (6), Authentication and Security (4), Testing, Deployment and DevOps (4). It has 10 easy, 19 medium, 1 hard questions, so you can start easy and work up to the harder ones.

Company type
IT services
Headquarters
Munich, Germany
Main India offices
Gurugram, Jaipur

Nagarro MERN Stack interview process

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

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

Solved for NagarroStart 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 would you structure the folders of a production Express API?

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

A component calls setState inside useEffect and the app goes into an infinite render loop. Why?

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

Write Express middleware that logs method, URL, status code and response time.

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

Design a secure forgot-password flow for a MERN application.

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

What does React.memo do and when is it useful?

Save to ▾
Show answer
React.memo wraps a component so it skips re-rendering when its props are shallowly equal to the previous props. It helps with expensive components that re-render often because the parent re-renders, such as rows in a large table. It fails if you pass new object, array or function props every render, so pair it with useMemo and useCallback. Measure with React DevTools Profiler before adding it.
06

What is the difference between var, let and const in JavaScript?

Save to ▾
Show answer
var is function-scoped, hoisted with the value undefined and can be redeclared. let and const are block-scoped and sit in the temporal dead zone until their declaration line runs. const blocks reassignment of the binding, but an object or array declared with const can still be mutated. In modern MERN code use const by default, let when the value must change, and avoid var.
07

What is the EventEmitter class and where is it used?

Save to ▾
Show answer
EventEmitter from the node:events module implements the publish-subscribe pattern. You register listeners with on or once and trigger them with emit, passing data. Many core objects extend it, including HTTP servers, streams and process. Always handle the error event, because an emitted error with no listener crashes the process. Remove listeners you no longer need to avoid the MaxListenersExceededWarning and memory leaks.
08

Set a refresh token in a secure httpOnly cookie after login.

Save to ▾
Show answer
Cookie flags carry most of the security. const refreshToken = jwt.sign({ sub: user.id }, process.env.REFRESH_SECRET, { expiresIn: '7d' }); const accessToken = jwt.sign({ sub: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '15m' }); res.cookie('refreshToken', refreshToken, { httpOnly: true, secure: true, sameSite: 'strict', path: '/api/auth/refresh', maxAge: 7 * 24 * 60 * 60 * 1000 }); res.json({ accessToken }); Read it later with the cookie-parser middleware via req.cookies.refreshToken.
09

What are Mongoose middleware hooks and give a common use case.

Save to ▾
Show answer
Mongoose middleware are functions that run before or after operations such as save, validate, deleteOne, findOneAndUpdate and aggregate. A classic pre-save hook hashes a password only if it was modified: if (!this.isModified('password')) return; this.password = await bcrypt.hash(this.password, 12). Post hooks are used for logging or syncing. Note that query middleware like findOneAndUpdate does not trigger save hooks.
10

Show the use of $push, $addToSet, $inc and $pull update operators.

Save to ▾
Show answer
Update operators change parts of a document atomically: db.posts.updateOne({ _id: id }, { $inc: { views: 1 } }) db.posts.updateOne({ _id: id }, { $addToSet: { tags: 'mongodb' } }) db.posts.updateOne({ _id: id }, { $push: { comments: { text: 'Nice', at: new Date() } } }) db.posts.updateOne({ _id: id }, { $pull: { tags: 'old' } }) $addToSet avoids duplicates, while $push always appends. Add $slice inside $push to cap an array's length.
11

How do arrow functions differ from regular functions?

Save to ▾
Show answer
Arrow functions have a shorter syntax and do not have their own this, arguments, super or new.target; they take this from the surrounding lexical scope. They cannot be used as constructors with new. This makes them ideal for callbacks, array methods and React event handlers. They are a poor choice for object methods that need this to refer to the object, or for prototype methods.
12

Write basic CRUD commands in mongosh for a users collection.

Save to ▾
Show answer
Core shell commands: db.users.insertOne({ name: 'Riya', email: 'riya@mail.com', age: 24 }) db.users.find({ age: { $gte: 21 } }, { name: 1, email: 1, _id: 0 }) db.users.updateOne({ email: 'riya@mail.com' }, { $set: { age: 25 } }) db.users.deleteMany({ isActive: false }) db.users.countDocuments({ city: 'Pune' }) The second argument of find is a projection that controls which fields are returned.
13

Should you store a JWT in localStorage or in an httpOnly cookie?

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

Write a Redux Toolkit slice that fetches products with createAsyncThunk.

Save to ▾
Show answer
The slice handles pending, fulfilled and rejected states. export const fetchProducts = createAsyncThunk('products/fetch', async () => { const res = await fetch('/api/products'); return res.json(); }); const productsSlice = createSlice({ name: 'products', initialState: { items: [], status: 'idle', error: null }, reducers: {}, extraReducers: (builder) => { builder .addCase(fetchProducts.pending, (s) => { s.status = 'loading'; }) .addCase(fetchProducts.fulfilled, (s, a) => { s.status = 'done'; s.items = a.payload; }) .addCase(fetchProducts.rejected, (s, a) => { s.status = 'failed'; s.error = a.error.message; }); } }); export default productsSlice.reducer;
15

Tell me about a deployment that went wrong and what you learned.

Save to ▾
Show answer
Situation: a release broke login for all users because a new environment variable was missing in production. Task: restore service fast. Action: I rolled back to the previous version within ten minutes, added the variable, and redeployed after testing on staging. Afterwards I added startup config validation and a post-deploy smoke test for login in our pipeline. Result: no config-related outage has happened since.
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

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.
18

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.
19

Write a docker-compose file to run a MERN app locally.

Save to ▾
Show answer
Three services on one network: services: mongo: image: mongo:8 volumes: - mongo-data:/data/db api: build: ./server environment: MONGO_URI: mongodb://mongo:27017/shop JWT_SECRET: dev-secret ports: - "5000:5000" depends_on: - mongo web: build: ./client ports: - "8080:80" depends_on: - api volumes: mongo-data: The API reaches the database through the service name mongo.
20

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.
21

What is the difference between props and state in React?

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

What is the difference between req.params, req.query and req.body?

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

What is NoSQL injection and how do you prevent it in a MongoDB app?

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

Implement page-based pagination for a products API with Mongoose.

Save to ▾
Show answer
Return items plus metadata. async function listProducts(req, res) { const page = Math.max(1, Number(req.query.page) || 1); const limit = Math.min(50, Number(req.query.limit) || 10); const [items, total] = await Promise.all([ Product.find().sort({ createdAt: -1 }) .skip((page - 1) * limit).limit(limit).lean(), Product.countDocuments() ]); res.json({ items, page, totalPages: Math.ceil(total / limit) }); } Capping limit prevents clients from requesting huge pages.
25

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.
26

What does lean() do in Mongoose and when should you use it?

Save to ▾
Show answer
By default Mongoose queries return full documents with change tracking, getters, virtuals and methods like save. Calling .lean() returns plain JavaScript objects, which uses much less memory and is noticeably faster. Use it for read-only endpoints such as lists and API responses. Skip it when you need to modify and save the document, or depend on virtuals and getters unless you add a lean plugin.
27

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.
28

How is Docker used in a MERN project?

Save to ▾
Show answer
Docker packages each service with its runtime and dependencies into an image so it runs the same on every machine. Typically the Express API gets an image built from a Node base, the React app is built and served by Nginx, and MongoDB runs from the official image locally while production often uses MongoDB Atlas. docker compose starts all services with one command, with networks and volumes for persistent data.
29

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.
30

Create a compound index for a user's order history query and verify it is used.

Save to ▾
Show answer
Query: orders of one user, newest first. db.orders.createIndex({ userId: 1, createdAt: -1 }) db.orders.find({ userId: ObjectId('...') }) .sort({ createdAt: -1 }) .limit(20) .explain('executionStats') Check that the winning plan shows IXSCAN, not COLLSCAN, and that totalDocsExamined is close to nReturned. In Mongoose, declare it with orderSchema.index({ userId: 1, createdAt: -1 }).

Tips to crack the Nagarro MERN Stack interview

  • Practise coding questions along with logical reasoning, as Nagarro assessments usually combine both.
  • Learn about Nagarro's flat, entrepreneurial culture and its CARING values for behavioural answers.
  • Be ready to explain testing approaches and agile practices, since many projects follow agile delivery with distributed teams.
  • 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; Nagarro interviewers usually ask follow-ups on your first answer.

Frequently asked questions

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

Candidates usually go through 4 stages: Online assessment (aptitude + reasoning); Coding test; Technical interview; Managerial or 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 Nagarro MERN Stack interview?

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

Are these the exact questions asked at Nagarro?

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

Where does Nagarro hire MERN Stack professionals in India?

Nagarro has large teams in Gurugram, Jaipur. Openings and locations change often, so check the Nagarro careers page and filter by city and experience.

MERN Stack questions for similar companies