Skip to content

Tech Mahindra MERN Stack Interview Questions & Answers

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

About Tech Mahindra hiring for MERN Stack roles

Tech Mahindra is an Indian IT services and consulting company and part of the Mahindra Group. It is known for its strong telecom and communications practice and also serves banking, manufacturing and healthcare clients. In India it hires for software engineers, test engineers, network engineers, data analysts and data engineers.

For MERN Stack roles, this Tech Mahindra practice set focuses most on Authentication and Security (5), Testing, Deployment and DevOps (5), MongoDB and Mongoose (4), Express.js and REST APIs (4). It has 17 easy, 11 medium, 2 hard questions, so you can start easy and work up to the harder ones.

Company type
IT services
Headquarters
Pune, India
Main India offices
Pune, Hyderabad, Bengaluru, Noida, Chennai

Tech Mahindra MERN Stack interview process

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

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

Solved for Tech MahindraStart 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 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.
02

How is Nginx used in front of a MERN application?

Save to ▾
Show answer
Nginx acts as a reverse proxy and web server. It serves the built React static files efficiently with caching and compression, proxies /api requests to Node instances, load balances across them, terminates HTTPS with certificates such as Let's Encrypt, and can apply rate limits and request size limits. For React Router, it uses try_files with a fallback to index.html so deep links work.
03

What is MongoDB and how is it different from a relational database?

Save to ▾
Show answer
MongoDB is a document database that stores data as flexible JSON-like documents in collections instead of rows in fixed tables. Related data can be embedded in one document, so many reads need no joins. Schemas are flexible, horizontal scaling through sharding is built in, and it supports indexes, aggregation and multi-document ACID transactions. Relational databases fit strongly structured data with many relationships and complex joins.
04

What is CSRF and how do SameSite cookies help prevent it?

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

What is a Promise and what are its states?

Save to ▾
Show answer
A Promise represents the eventual result of an asynchronous operation. It starts in the pending state and settles once, either fulfilled with a value or rejected with a reason, and never changes after that. You consume it with then, catch and finally, or with await inside an async function. Promises replaced deeply nested callbacks in Node.js APIs and make error propagation through a chain much easier.
06

What is Node.js and how does it handle many requests on a single thread?

Save to ▾
Show answer
Node.js is a JavaScript runtime built on the V8 engine and libuv. Your JavaScript runs on one main thread, but I/O such as network calls, file reads and database queries is non-blocking. Node hands that work to the operating system or the libuv thread pool and continues with other requests; callbacks run when results are ready. This makes it efficient for I/O-heavy APIs, but weak for CPU-heavy work.
07

Write a register endpoint that hashes the password with bcrypt.

Save to ▾
Show answer
Validate, check duplicates and hash before saving. import bcrypt from 'bcrypt'; router.post('/register', async (req, res) => { const { name, email, password } = req.body; if (!email || !password || password.length < 8) { return res.status(400).json({ message: 'Invalid input' }); } const exists = await User.findOne({ email: email.toLowerCase() }); if (exists) return res.status(409).json({ message: 'Email already registered' }); const hash = await bcrypt.hash(password, 12); const user = await User.create({ name, email, password: hash }); res.status(201).json({ id: user._id, name: user.name }); }); A unique index on email still guards against races.
08

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

What is the difference between unit, integration and end-to-end tests in a MERN app?

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

Write a counter component using useState.

Save to ▾
Show answer
Use the functional updater when the new value depends on the old one. import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount((c) => c + 1)}>+</button> <button onClick={() => setCount((c) => c - 1)}>-</button> <button onClick={() => setCount(0)}>Reset</button> </div> ); }
11

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; }
12

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

Set up React Router with a layout, a list page and a detail page using useParams.

Save to ▾
Show answer
Data router setup with nested routes: import { createBrowserRouter, RouterProvider, Outlet, useParams } from 'react-router'; const Layout = () => (<><Navbar /><Outlet /></>); const ProductPage = () => { const { id } = useParams(); return <ProductDetails id={id} />; }; const router = createBrowserRouter([ { path: '/', element: <Layout />, children: [ { index: true, element: <Home /> }, { path: 'products', element: <ProductList /> }, { path: 'products/:id', element: <ProductPage /> } ] } ]); export default function App() { return <RouterProvider router={router} />; }
14

What are BSON and ObjectId in MongoDB?

Save to ▾
Show answer
BSON is the binary format MongoDB uses to store documents. It extends JSON with types like Date, ObjectId, Decimal128, binary data and 32 or 64-bit integers, and is fast to traverse. ObjectId is the default 12-byte _id value made of a 4-byte timestamp, a 5-byte random value and a 3-byte counter. Because it starts with a timestamp, ObjectIds roughly sort by creation time.
15

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

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

Write a unit test for a function that calculates a cart total.

Save to ▾
Show answer
Vitest and Jest share the same syntax. // cart.js export const cartTotal = (items) => items.reduce((sum, i) => sum + i.price * i.qty, 0); // cart.test.js import { describe, it, expect } from 'vitest'; import { cartTotal } from './cart.js'; describe('cartTotal', () => { it('returns 0 for an empty cart', () => { expect(cartTotal([])).toBe(0); }); it('multiplies price by quantity', () => { expect(cartTotal([{ price: 100, qty: 2 }, { price: 50, qty: 1 }])).toBe(250); }); });
18

Write an aggregation that counts orders and sums revenue per status.

Save to ▾
Show answer
Group by status and sort by revenue. db.orders.aggregate([ { $match: { createdAt: { $gte: ISODate('2026-01-01') } } }, { $group: { _id: '$status', orders: { $sum: 1 }, revenue: { $sum: '$amount' } } }, { $sort: { revenue: -1 } }, { $project: { status: '$_id', orders: 1, revenue: 1, _id: 0 } } ]) In Mongoose the same array goes into Order.aggregate([...]).
19

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

Tell me about a time you found and fixed a security issue in an application.

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

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

What are Jest and Vitest, and what is the philosophy of React Testing Library?

Save to ▾
Show answer
Jest and Vitest are JavaScript test runners with assertions, mocking and coverage; Vitest is Vite-native, very fast and Jest-compatible, so it is common in new React projects. React Testing Library renders components and encourages testing them the way users use them: find elements by role, label or text, fire user events, and assert on visible output, instead of testing internal state or implementation details.
23

Read a JSON file and write an updated version using fs/promises and async/await.

Save to ▾
Show answer
The promise-based fs API keeps code clean and non-blocking. import { readFile, writeFile } from 'node:fs/promises'; async function addUser(user) { try { const data = JSON.parse(await readFile('users.json', 'utf8')); data.push(user); await writeFile('users.json', JSON.stringify(data, null, 2)); } catch (err) { console.error('Failed to update file', err); throw err; } } Avoid readFileSync inside request handlers because it blocks the event loop.
24

What is the difference between package.json and package-lock.json, and what do ^ and ~ mean?

Save to ▾
Show answer
package.json lists dependencies with version ranges, scripts and metadata. package-lock.json records the exact installed versions of every package, including nested ones, so every machine and CI build gets the same tree. Commit both and use npm ci in pipelines. A caret like ^4.18.2 allows minor and patch updates below 5.0.0; a tilde like ~4.18.2 allows only patch updates below 4.19.0.
25

Fast typing in a search box sometimes shows results for an older query. What causes this and how do you fix it?

Save to ▾
Show answer
It is a race condition: responses arrive out of order, so a slow earlier request overwrites results of a newer one. In the effect, use an AbortController and abort the previous request in the cleanup, or keep an ignore flag set to true during cleanup and skip setState when it is set. Debouncing reduces requests, and TanStack Query handles this automatically by keying results to the query.
26

What are the common ways to render content conditionally in React?

Save to ▾
Show answer
Use an early return for whole-component cases like loading, an if statement outside JSX, the ternary operator for either-or markup, and logical && for show-or-hide. Be careful with && on numbers: count && <Badge /> renders 0 when count is zero, so use count > 0 && <Badge />. For many states, map a status value to components with an object lookup.
27

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

Write a reusable validation middleware for Express using zod.

Save to ▾
Show answer
Validate before the controller runs and return 400 on failure. import { z } from 'zod'; const validate = (schema) => (req, res, next) => { const result = schema.safeParse(req.body); if (!result.success) { return res.status(400).json({ errors: result.error.issues }); } req.body = result.data; next(); }; const userSchema = z.object({ name: z.string().min(2), email: z.string().email() }); router.post('/users', validate(userSchema), createUser);
29

Which HTTP status codes should a REST API commonly return?

Save to ▾
Show answer
Use 200 OK for successful reads and updates, 201 Created after a POST that creates a resource, and 204 No Content for successful deletes. Use 400 for invalid input, 401 when authentication is missing or invalid, 403 when the user is authenticated but not allowed, 404 for missing resources, 409 for conflicts such as duplicate email, 422 for validation errors, 429 for rate limits and 500 for unexpected server errors.
30

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.

Tips to crack the Tech Mahindra MERN Stack interview

  • Read about telecom basics like 4G, 5G and network operations, since communications is Tech Mahindra's largest vertical.
  • Practise English essay and verbal ability sections, which often appear in Tech Mahindra online assessments.
  • Revise SQL and one programming language, and prepare a clear two-minute explanation of your project.
  • 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; Tech Mahindra interviewers usually ask follow-ups on your first answer.

Frequently asked questions

How many rounds are there in the Tech Mahindra MERN Stack interview?

Candidates usually go through 4 stages: Online assessment (aptitude + English essay); Coding test; 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 Tech Mahindra MERN Stack interview?

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

Are these the exact questions asked at Tech Mahindra?

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

Where does Tech Mahindra hire MERN Stack professionals in India?

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

MERN Stack questions for similar companies