36 practice questions with answers for MERN Stack interviews in Coimbatore.
MERN Stack jobs in Coimbatore
Coimbatore has a growing IT-services and engineering-services market around TIDEL Park and its SEZs, supported by a large pool of engineering graduates. Many roles are with delivery centres of bigger IT firms.
Below are 36 questions that match the mix of service, product and domain employers hiring mern stack developers in Coimbatore.
Solved for CoimbatoreStart 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 React protect against XSS and where can XSS still happen?
React escapes values rendered in JSX, so user text containing script tags is shown as text, not executed. XSS can still happen through dangerouslySetInnerHTML with unsanitised HTML, javascript: URLs in href attributes, injecting user data into script tags during SSR, or unsafe third-party scripts. Sanitise any HTML with DOMPurify, validate URLs, set a Content Security Policy, and keep tokens out of JavaScript-readable storage.
02
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.
03
Your script crashes with out of memory while reading a 5 GB log file. How would you rewrite it?
fs.readFile loads the whole file into memory, which exceeds the heap. Use a stream instead: fs.createReadStream with readline lets you process one line at a time with for await, keeping memory flat. If you need to transform and write output, connect read, transform and write streams with pipeline so backpressure and errors are handled. Increasing --max-old-space-size only hides the real problem.
04
Write a reusable validation middleware for Express using zod.
Situation: in my internship, a senior reviewer rejected my pull request because my components were large and repeated logic. Task: fix it without missing the sprint deadline. Action: I asked for examples, split the page into smaller components, extracted a custom hook for the shared fetching logic and added prop types. Result: the PR was approved the next day, and the reviewer used my hook in another feature.
06
Fast typing in a search box sometimes shows results for an older query. What causes this and how do you fix it?
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.
A JSON Web Token is a compact, URL-safe token made of three Base64URL-encoded parts separated by dots: the header with algorithm and type, the payload with claims like sub, role and exp, and the signature created from the header and payload using a secret or private key. The signature proves the token was not altered, but the payload is readable by anyone, so never put passwords or sensitive data in it.
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.
09
Your MERN app works on your laptop but crashes after deployment to a server. How do you troubleshoot?
Read the server logs first. Common causes are missing environment variables, a different Node version, the database host or IP allowlist blocking the server, hardcoded localhost URLs, wrong PORT handling, devDependencies missing in production, case-sensitive file names on Linux, and the frontend API base URL pointing to localhost. Reproduce with the same Node version or a Docker image, and validate config at startup.
10
Every time a user types in an input inside a list item, the input loses focus. What could be the cause?
The component is likely being remounted on each render. Common causes are generating keys randomly, such as key={Math.random()}, defining a component inside another component's body so it gets a new identity every render, or using index keys while the list reorders. Use stable ids as keys and move inner component definitions to the module level so React preserves their DOM and state.
11
How do arrow functions differ from regular functions?
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
What is React and how does the virtual DOM help performance?
React is a JavaScript library for building user interfaces from reusable components. When state changes, React re-renders components into a lightweight in-memory tree called the virtual DOM, compares it with the previous tree through reconciliation, and applies only the minimal changes to the real DOM. Direct DOM updates are expensive, so batching and diffing keep updates efficient while letting developers write declarative code.
13
Walk me through a MERN project you built, end to end.
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.
14
A for loop using var with setTimeout inside prints 3, 3, 3 instead of 0, 1, 2. Why, and how do you fix it?
var is function-scoped, so all three callbacks close over the same variable, which has become 3 by the time the timers fire. The simplest fix is to declare the loop variable with let, because let creates a fresh binding for every iteration. Older fixes include wrapping the body in an immediately invoked function or passing i as the third argument to setTimeout.
15
A developer accidentally pushed the .env file with the MongoDB password and JWT secret to a public repository. What do you do?
Treat the secrets as compromised immediately. Rotate the MongoDB user password, the JWT secret and any API keys; rotating the JWT secret logs everyone out, which is acceptable. Check database and cloud logs for suspicious access. Remove the file, add .env to .gitignore, and purge it from history with a tool like git filter-repo, though rotation matters more. Enable secret scanning and pre-commit hooks to prevent repeats.
16
What is the difference between controlled and uncontrolled components?
In a controlled component, form input values live in React state and change through onChange, so React is the single source of truth, which makes validation and conditional UI easy. In an uncontrolled component, the DOM holds the value and you read it with a ref or FormData when needed. Uncontrolled inputs mean fewer re-renders and suit simple forms and file inputs; libraries like React Hook Form use this approach.
17
Some tests pass locally but fail randomly in CI. How do you handle flaky tests?
Rerun to confirm flakiness, then find the cause instead of adding retries. Common causes are shared database state between tests, tests depending on run order, real timers and dates, network calls to real services, and E2E tests using fixed waits instead of waiting for elements. Isolate data per test, mock time and external APIs, use proper async waits, and quarantine a flaky test with a ticket until fixed.
18
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.
19
How do environment variables work in a Vite React app compared to a Node.js backend?
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.
20
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.
21
Write a React Testing Library test for a counter button.
Query by role and simulate real user events.
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Counter from './Counter';
test('increments the count when + is clicked', async () => {
const user = userEvent.setup();
render(<Counter />);
expect(screen.getByText('Count: 0')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: '+' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
toBeInTheDocument comes from @testing-library/jest-dom.
22
How does routing work in a React single-page app using React Router?
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.
23
Write a docker-compose file to run a MERN app locally.
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.
24
How does error-handling middleware work in Express, and what changed in Express 5?
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.
25
Your chat feature uses Socket.IO and must now run on multiple Node instances. What changes are needed?
Each instance only knows its own connected sockets, so a message emitted on one would not reach users on another. Add the Socket.IO Redis adapter, or a similar pub/sub adapter, so events are broadcast across instances. Enable sticky sessions at the load balancer if HTTP long-polling fallback is used. Store presence and room membership in Redis, persist messages in MongoDB, and authenticate sockets with tokens during the handshake.
26
What are a Mongoose schema and model, and how does validation work?
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.
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.
28
What practical steps do you take to sanitise and validate input in an Express and MongoDB API?
Validate every request body, params and query against a schema with zod or Joi, rejecting unknown fields and wrong types. Apply body size limits with express.json({ limit: '100kb' }). Strip MongoDB operator keys from input with a small sanitising middleware or library, and keep Mongoose strict mode on. Escape or sanitise HTML with DOMPurify before storing rich text, and validate ObjectIds before querying.
29
Write an async helper that retries a failing call with exponential backoff.
Wait longer after each failure and give up after a limit.
async function retry(fn, retries = 3, base = 500) {
for (let attempt = 0; ; attempt++) {
try {
return await fn();
} catch (err) {
if (attempt >= retries) throw err;
const wait = base * 2 ** attempt + Math.random() * 100;
await new Promise((r) => setTimeout(r, wait));
}
}
}
The random jitter stops many clients from retrying at the same moment.
30
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.
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.
32
Write a central error-handling middleware with a custom AppError class.
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.
34
Your API becomes unresponsive whenever a user uploads an image for resizing. What is happening and how do you fix it?
Resizing is CPU-bound work running on the main thread, so it blocks the event loop and every other request waits. Fix it by moving the work off the main thread: use a worker_threads pool, a native library like sharp that works in the libuv pool, or better, push a job to a queue such as BullMQ with Redis and process it in a separate worker service, then notify the client.
35
What strategies can you use to version a REST API?
The most common approach is URL versioning such as /api/v1/orders, which is simple and cache friendly. Alternatives are a custom header or a media type like Accept: application/vnd.app.v2+json, which keeps URLs clean but is harder to test in a browser. Whatever you choose, make additive changes without a new version, announce deprecations, and run old and new versions side by side during migration.
36
What is the output order of console.log('A'), setTimeout(() => console.log('B'), 0), Promise.resolve().then(() => console.log('C')) and console.log('D')?
The output is A, D, C, B. A and D are synchronous and run immediately on the call stack. The Promise callback C goes into the microtask queue, and the setTimeout callback B goes into the macrotask queue. After the synchronous code finishes, the event loop drains all microtasks first, printing C, and only then runs the timer callback, printing B, even with a 0 ms delay.
Few big employers listed in Coimbatore?
Many Coimbatore candidates also apply to teams in Chennai and to remote or hybrid roles. Practise the Chennai set as well.
Which companies hire MERN Stack professionals in Coimbatore?
Companies with large offices in Coimbatore include many IT services and product firms. Use their company pages below to practise employer-specific sets.
Are MERN Stack interviews in Coimbatore different from other cities?
The questions depend more on the company than the city. Coimbatore's mix of employers decides the style: Many roles are with delivery centres of bigger IT firms
How do I find MERN Stack jobs in Coimbatore?
Shortlist companies with Coimbatore offices, keep your CV focused on MERN Stack projects, apply on company career pages and job portals with the Coimbatore filter, and practise the questions on this page before each interview.