MERN Stack Interview Questions in Thiruvananthapuram
36 practice questions with answers for MERN Stack interviews in Thiruvananthapuram.
MERN Stack jobs in Thiruvananthapuram
Thiruvananthapuram's Technopark is one of India's oldest IT parks, hosting IT-services, product and engineering-services companies. Data and testing teams here often work with global clients in finance, travel and healthcare.
Below are 36 questions that match the mix of service, product and domain employers hiring mern stack developers in Thiruvananthapuram.
Solved for ThiruvananthapuramStart 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
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.
02
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.
03
Why are functional components preferred over class components today?
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.
04
Your Express API slows down badly during peak traffic. How do you find and fix the bottleneck?
Measure first: add request timing logs or APM tracing to find slow endpoints, then check whether time goes to the database, external calls or CPU. Use explain() for slow queries and add indexes, cache hot read endpoints in Redis, enable compression, paginate large responses and remove synchronous code from handlers. Then scale horizontally with multiple instances behind a load balancer and load test with k6 or autocannon.
05
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.
06
What is Node.js and how does it handle many requests on a single thread?
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.
A fragment, written <>...</> or <Fragment key={id}>, groups children without adding an extra DOM element, which keeps tables and flex layouts valid. A portal, created with createPortal(child, domNode), renders children into a different DOM node such as document.body while keeping them in the same React tree, so context and event bubbling still work. Portals are used for modals, tooltips and toasts that must escape overflow hidden containers.
08
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.
09
How do you plan a Node.js major version upgrade for a project your team maintains?
Situation: our services were on a Node version nearing end of life. Task: I owned the upgrade to the current LTS. Action: I read the changelog for breaking changes, upgraded locally, ran the test suite, fixed deprecated APIs and incompatible native packages, and rolled out to staging, then one production service, watching metrics. Result: all services moved within two sprints with no incidents, and I added an LTS calendar to our planning.
10
Write a role-based authorization middleware for Express.
Promise.all resolves with all results when every Promise fulfils and rejects as soon as any one rejects. Promise.allSettled always waits for all and returns status objects, useful when partial failure is fine. Promise.race settles with the first Promise to settle, often used for timeouts. Promise.any resolves with the first fulfilment and rejects with an AggregateError only if all reject, useful for trying multiple mirrors.
12
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.
13
Your React production bundle is 3 MB and the first load is slow on mobile. What steps do you take?
Analyse the bundle to find the largest modules. Split code by route with React.lazy, lazy load heavy libraries like charts and editors, replace large dependencies with lighter ones, import only needed functions so tree shaking works, and remove unused polyfills. Compress images, serve assets from a CDN with Brotli and long cache headers, and consider SSR or static rendering for landing pages. Track Core Web Vitals after each change.
14
The business wants total sales per category for the last 30 days. How would you build it in MongoDB?
Use an aggregation pipeline: $match orders with status paid and createdAt in the last 30 days, using an index on createdAt; $unwind the items array; $group by items.category summing items.price times items.qty; then $sort by total descending. If the report is viewed often, precompute daily totals into a summary collection with a scheduled job or $merge, so the dashboard reads small documents.
15
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.
Each loop iteration goes through phases: timers runs expired setTimeout and setInterval callbacks; pending callbacks runs some deferred system callbacks; poll waits for and runs I/O callbacks; check runs setImmediate callbacks; close callbacks handles events like socket close. Between every callback, Node drains process.nextTick callbacks and then Promise microtasks. Knowing this explains why setImmediate inside an I/O callback always runs before a setTimeout of 0.
17
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.
18
Create an AuthContext with a provider and a custom hook.
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.
20
What is mocking and when should you mock in tests?
Mocking replaces a real dependency with a controlled fake so tests are fast, isolated and deterministic. Mock things you do not own or that are slow or unpredictable: payment gateways, email services, third-party APIs, time and random values. In React tests, Mock Service Worker intercepts network requests. Avoid mocking everything, especially your own database layer in integration tests, or tests will pass while real code fails.
21
Write a function to flatten a nested array without using Array.prototype.flat.
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.
22
Tell me about a time you disagreed with a teammate about an API design decision.
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.
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.
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.
26
What is the difference between process.nextTick, setImmediate and setTimeout(fn, 0)?
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.
27
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.
28
Write a production Dockerfile for a Node.js Express API.
Keep the image small and run as a non-root user.
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev
COPY src ./src
USER node
EXPOSE 5000
CMD ["node", "src/server.js"]
Copying package files first lets Docker cache the dependency layer, so code changes rebuild quickly. Add a .dockerignore with node_modules and .env.
29
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.
30
Write a unit test for a function that calculates a cart total.
On every pull request, continuous integration installs dependencies with npm ci, runs lint, type checks, unit and integration tests, and builds the frontend. On merge to main, continuous delivery builds Docker images or artifacts, tags them with the commit, pushes to a registry, deploys to staging, runs smoke tests and then promotes to production, often with manual approval. GitHub Actions, GitLab CI and Jenkins are common tools.
32
What is CORS and how do you configure it in an Express API?
CORS is a browser security mechanism that blocks a page from reading responses from a different origin unless the server allows it through headers like Access-Control-Allow-Origin. For non-simple requests the browser sends a preflight OPTIONS request first. In Express, use the cors package with an explicit allowlist, for example cors({ origin: ['https://app.example.com'], credentials: true }), instead of allowing every origin with credentials.
33
How would you achieve zero-downtime deployments for an Express API?
Run at least two instances behind a load balancer and use rolling or blue-green deployments: start new instances, wait for health and readiness checks to pass, shift traffic, then drain and stop old instances with graceful shutdown. PM2 reload or Kubernetes rolling updates handle this. Keep database migrations backward compatible, adding fields before code uses them, so old and new versions can run together.
34
How do you debug a JavaScript bug that a user reports but you cannot reproduce locally?
Situation: a user reported a checkout button doing nothing, but it worked for me. Task: find the cause quickly. Action: I asked for browser, device and steps, checked our error-tracking logs, and found a TypeError only on an older Safari version due to an unsupported method. I reproduced it on a cloud device, added a polyfill and a test. Result: the fix shipped the same day and I added browser targets to our build.
35
Why does React need keys in lists, and why is using the array index risky?
Keys tell React which list item is which between renders, so it can reuse, move or remove the correct DOM nodes and component state. Use stable unique ids, such as a MongoDB _id. Index keys break when items are inserted, removed or reordered: state such as input text or checkbox values can attach to the wrong item, and rendering becomes less efficient. Indexes are acceptable only for static lists.
36
What is NoSQL injection and how do you prevent it in a MongoDB app?
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.
Few big employers listed in Thiruvananthapuram?
Many Thiruvananthapuram candidates also apply to teams in Bangalore and to remote or hybrid roles. Practise the Bangalore set as well.
Which companies hire MERN Stack professionals in Thiruvananthapuram?
Companies with large offices in Thiruvananthapuram include many IT services and product firms. Use their company pages below to practise employer-specific sets.
Are MERN Stack interviews in Thiruvananthapuram different from other cities?
The questions depend more on the company than the city. Thiruvananthapuram's mix of employers decides the style: Data and testing teams here often work with global clients in finance, travel and healthcare
How do I find MERN Stack jobs in Thiruvananthapuram?
Shortlist companies with Thiruvananthapuram offices, keep your CV focused on MERN Stack projects, apply on company career pages and job portals with the Thiruvananthapuram filter, and practise the questions on this page before each interview.