Skip to content

TCS MERN Stack Interview Questions & Answers

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

About TCS hiring for MERN Stack roles

Tata Consultancy Services is a Tata Group company and one of the largest IT services and consulting firms in the world. It delivers application development, testing, cloud, data and analytics services to clients in banking, retail, manufacturing and other industries. In India it hires freshers and experienced staff for software testing, data engineering, BI reporting and analytics roles across its delivery centres.

For MERN Stack roles, this TCS practice set focuses most on Authentication and Security (7), React Fundamentals (5), Node.js Core (4), Modern JavaScript (ES6+) (4). It has 15 easy, 14 medium, 1 hard questions, so you can start easy and work up to the harder ones.

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

TCS MERN Stack interview process

  1. TCS NQT online assessment (aptitude + coding)
  2. Technical interview
  3. Managerial round
  4. HR round

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

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

Why do applications use both access tokens and refresh tokens?

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

Your Node.js API runs on an 8-core server but CPU monitoring shows only one core busy. What do you do?

Save to ▾
Show answer
A Node process runs JavaScript on a single thread, so one instance uses about one core. Run multiple instances: PM2 in cluster mode with -i max, the cluster module, or several containers behind a load balancer such as Nginx. Because instances do not share memory, move sessions, caches and rate-limit counters to Redis, and make sure the app is stateless so any instance can serve any request.
03

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

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

Explain hoisting in JavaScript with an example.

Save to ▾
Show answer
Hoisting means declarations are processed before code runs. Function declarations are hoisted fully, so you can call them before they appear. var declarations are hoisted but initialised to undefined, so console.log(x) before var x = 5 prints undefined. let, const and class declarations are hoisted too, but accessing them before the declaration throws a ReferenceError because of the temporal dead zone. Function expressions assigned to variables follow the variable rules.
06

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} />; }
07

Write a role-based authorization middleware for Express.

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

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

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

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

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

Your app needs user, editor and admin roles with different permissions. How would you implement it?

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

Write a Supertest integration test for a POST /api/users endpoint.

Save to ▾
Show answer
Import the app, not the running server. import request from 'supertest'; import app from '../src/app.js'; describe('POST /api/users', () => { it('creates a user', async () => { const res = await request(app) .post('/api/users') .send({ name: 'Aman', email: 'aman@test.com' }) .expect(201); expect(res.body.email).toBe('aman@test.com'); }); it('rejects invalid email', async () => { await request(app).post('/api/users').send({ name: 'A', email: 'x' }).expect(400); }); }); Connect to mongodb-memory-server in a beforeAll hook.
14

What is the difference between process.nextTick, setImmediate and setTimeout(fn, 0)?

Save to ▾
Show answer
process.nextTick queues a callback to run right after the current operation, before Promise microtasks and before the event loop continues. setImmediate runs in the check phase after poll. setTimeout with 0 runs in the timers phase once at least about 1 ms has passed. Overusing nextTick recursively can starve I/O, so setImmediate is the safer way to defer heavy work.
15

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

What are a Mongoose schema and model, and how does validation work?

Save to ▾
Show answer
A schema defines the shape of documents: field types, defaults, required flags, validators, indexes and options like timestamps. A model is compiled from a schema with mongoose.model('User', userSchema) and provides query methods like find, create and updateOne. Built-in validators include required, min, max, enum and match, and you can add custom validators. Validation runs on save and create; for updates, set runValidators: true.
17

Write a useDebounce hook and use it for a search input.

Save to ▾
Show answer
The hook returns a value that updates only after a delay. function useDebounce(value, delay = 400) { const [debounced, setDebounced] = useState(value); useEffect(() => { const id = setTimeout(() => setDebounced(value), delay); return () => clearTimeout(id); }, [value, delay]); return debounced; } function Search() { const [q, setQ] = useState(''); const term = useDebounce(q); const { data } = useFetch(`/api/products?search=${encodeURIComponent(term)}`); return <input value={q} onChange={(e) => setQ(e.target.value)} />; }
18

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

Write a reusable useFetch custom hook.

Save to ▾
Show answer
It returns data, error and loading state and aborts stale requests. function useFetch(url) { const [state, setState] = useState({ data: null, error: null, loading: true }); useEffect(() => { const controller = new AbortController(); setState((s) => ({ ...s, loading: true })); fetch(url, { signal: controller.signal }) .then((r) => { if (!r.ok) throw new Error(r.status); return r.json(); }) .then((data) => setState({ data, error: null, loading: false })) .catch((error) => { if (error.name !== 'AbortError') setState({ data: null, error, loading: false }); }); return () => controller.abort(); }, [url]); return state; }
20

Fetch a list of users from an API inside useEffect with proper cleanup.

Save to ▾
Show answer
AbortController cancels the request if the component unmounts. function Users() { const [users, setUsers] = useState([]); const [error, setError] = useState(null); useEffect(() => { const controller = new AbortController(); fetch('/api/users', { signal: controller.signal }) .then((r) => r.json()) .then(setUsers) .catch((e) => { if (e.name !== 'AbortError') setError(e); }); return () => controller.abort(); }, []); if (error) return <p>Failed to load</p>; return <ul>{users.map((u) => <li key={u._id}>{u.name}</li>)}</ul>; }
21

Write a controlled login form that submits to an API.

Save to ▾
Show answer
One state object and a shared change handler. function LoginForm() { const [form, setForm] = useState({ email: '', password: '' }); const onChange = (e) => setForm({ ...form, [e.target.name]: e.target.value }); const onSubmit = async (e) => { e.preventDefault(); const res = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) }); if (!res.ok) alert('Invalid credentials'); }; return ( <form onSubmit={onSubmit}> <input name='email' value={form.email} onChange={onChange} /> <input name='password' type='password' value={form.password} onChange={onChange} /> <button>Login</button> </form> ); }
22

Write a Mongoose schema for a user with validation and timestamps.

Save to ▾
Show answer
A typical schema: import mongoose from 'mongoose'; const userSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true, maxlength: 60 }, email: { type: String, required: true, unique: true, lowercase: true }, password: { type: String, required: true, minlength: 8, select: false }, role: { type: String, enum: ['user', 'admin'], default: 'user' } }, { timestamps: true }); export const User = mongoose.model('User', userSchema); select: false hides the password from queries by default.
23

Show how to create and use a custom EventEmitter.

Save to ▾
Show answer
Extend EventEmitter to emit domain events. import { EventEmitter } from 'node:events'; class OrderService extends EventEmitter { place(order) { // save order... this.emit('order:placed', order); } } const orders = new OrderService(); orders.on('order:placed', (o) => sendEmail(o.userEmail)); orders.once('order:placed', () => console.log('first order')); orders.place({ id: 1, userEmail: 'a@b.com' }); Listeners run synchronously in registration order.
24

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

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

How would you explain a technical decision, such as choosing REST over GraphQL, to a non-technical manager?

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

Write a function to flatten a nested array without using Array.prototype.flat.

Save to ▾
Show answer
Recursion with reduce is the cleanest approach. function flatten(arr) { return arr.reduce((acc, item) => Array.isArray(item) ? acc.concat(flatten(item)) : acc.concat(item), []); } flatten([1, [2, [3, [4]]], 5]); // [1, 2, 3, 4, 5] For very deep arrays, an iterative version with an explicit stack avoids hitting the recursion limit.
28

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

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

Compare session-based authentication with JWT-based authentication.

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

Tips to crack the TCS MERN Stack interview

  • Practise TCS NQT style numerical, verbal and reasoning sections along with two basic coding problems under strict time limits.
  • Be ready to explain your final-year project, SQL basics and core concepts like OOP, DBMS and software testing life cycle.
  • Read about TCS service lines such as BFSI and its iON and Ignio platforms to answer why you want to join.
  • 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; TCS interviewers usually ask follow-ups on your first answer.

Frequently asked questions

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

Candidates usually go through 4 stages: TCS NQT online assessment (aptitude + coding); Technical interview; 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 TCS MERN Stack interview?

This practice set leans on Authentication and Security (7), React Fundamentals (5), Node.js Core (4), Modern JavaScript (ES6+) (4). Revise those first, then practise explaining one or two of your own projects end to end, because most TCS interviewers ask you to walk through real work.

Are these the exact questions asked at TCS?

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

Where does TCS hire MERN Stack professionals in India?

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

MERN Stack questions for similar companies