Skip to content

MERN Stack Interview Questions in Kochi

36 practice questions with answers for MERN Stack interviews in Kochi.

MERN Stack jobs in Kochi

Kochi's Infopark and SmartCity host IT-services firms, product companies and start-ups, making it Kerala's largest tech job market along with Thiruvananthapuram. Testing and data roles are common in its service and product teams.

Below are 36 questions that match the mix of service, product and domain employers hiring mern stack developers in Kochi.

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

What is the Context API and when should you avoid it?

Save to ▾
Show answer
Context passes data through the component tree without prop drilling. You create it with createContext, provide a value with a Provider and read it with useContext, or the newer use API. It suits low-frequency global data like theme, language and logged-in user. Avoid it for frequently changing large state, because every consumer re-renders when the value changes; split contexts or use Zustand or Redux Toolkit instead.
02

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

How have you helped junior developers improve their React skills?

Save to ▾
Show answer
Situation: two freshers joined my team and their PRs had repeated effect bugs. Task: help them ramp up without slowing the sprint. Action: I ran short weekly sessions on effects, keys and state structure, paired with them on real tickets, and wrote a review checklist. I gave specific, kind comments in reviews. Result: within two months their PRs needed far fewer changes, and one of them now runs the sessions.
05

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

Your API becomes unresponsive whenever a user uploads an image for resizing. What is happening and how do you fix it?

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

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

Compare Promise.all, Promise.allSettled, Promise.race and Promise.any.

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

What are React fragments and portals?

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

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

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

Group an array of order objects by their status using reduce.

Save to ▾
Show answer
reduce builds an object whose keys are statuses and values are arrays. const grouped = orders.reduce((acc, order) => { (acc[order.status] ||= []).push(order); return acc; }, {}); // { paid: [...], pending: [...] } Newer runtimes also offer Object.groupBy(orders, (o) => o.status), which returns the same shape with a null prototype.
14

How do you debug a JavaScript bug that a user reports but you cannot reproduce locally?

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

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

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

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

Your API has 40 routes and each returns errors in a different format. How would you standardise this?

Save to ▾
Show answer
Create a custom AppError class with statusCode and code fields, throw it from services and controllers, and handle every error in one central error middleware that returns a consistent shape such as { success: false, error: { code, message, details } }. Map validation, Mongoose cast and duplicate key errors to proper status codes there. Document the format in OpenAPI so the React team handles errors uniformly.
19

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

How do class component lifecycle methods map to hooks?

Save to ▾
Show answer
componentDidMount maps to useEffect with an empty dependency array. componentDidUpdate maps to useEffect with specific dependencies. componentWillUnmount maps to the cleanup function returned from useEffect. shouldComponentUpdate is roughly React.memo, and getDerivedStateFromProps is usually replaced by computing values during render. The mindset shifts from lifecycle moments to synchronising with external systems whenever certain values change.
21

What is the difference between CommonJS and ES modules in Node.js?

Save to ▾
Show answer
CommonJS uses require and module.exports, loads synchronously and is the historic Node default. ES modules use import and export, are statically analysable, support top-level await and enable tree shaking. Node treats .mjs files, or .js files when package.json has type: module, as ESM. Modern Node versions can even require synchronous ES modules, but mixing systems still needs care, so new MERN projects usually pick ESM throughout.
22

How do you protect certain routes in React so that only logged-in users can access them?

Save to ▾
Show answer
Create a ProtectedRoute or layout component that reads auth state from context. If the user is not authenticated, return <Navigate to='/login' replace state={{ from: location }} />, otherwise render the Outlet or children. Show a loader while the session check is pending to avoid flicker. Remember that this is only for user experience; real protection must happen on the Express API by verifying tokens on every request.
23

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

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

Create a basic HTTP server in Node.js without Express that returns JSON.

Save to ▾
Show answer
The built-in node:http module is enough for simple servers. import http from 'node:http'; const server = http.createServer((req, res) => { if (req.method === 'GET' && req.url === '/health') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ status: 'ok' })); } res.writeHead(404); res.end(); }); server.listen(3000, () => console.log('Listening on 3000')); Express adds routing, middleware and body parsing on top of this.
26

What is PM2 and why is it used to run Node.js in production?

Save to ▾
Show answer
PM2 is a process manager for Node.js. It keeps the app alive by restarting it after crashes, runs multiple instances in cluster mode to use all CPU cores, supports zero-downtime reloads with pm2 reload, manages logs and starts apps on server boot. Configuration lives in an ecosystem.config.js file. On container platforms like Kubernetes, the orchestrator often replaces PM2's restart and scaling role.
27

After deploying a React app, refreshing on a page like /dashboard shows a 404 error. Why, and how do you fix it?

Save to ▾
Show answer
With client-side routing, /dashboard exists only inside React Router, not as a file on the server. When the browser requests it directly, the web server finds no file and returns 404. Configure the server to fall back to index.html for unknown paths: try_files $uri /index.html in Nginx, a rewrite rule on static hosts, or a catch-all route in Express that serves index.html after the API routes.
28

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

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

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

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

Describe a mistake you made with data and how you handled it.

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

When should you use useReducer instead of useState?

Save to ▾
Show answer
Use useReducer when state has multiple related fields, when the next state depends on complex logic, or when many event handlers update state in different ways. A reducer is a pure function (state, action) => newState that centralises transitions and is easy to unit test, for example a cart with add, remove, change quantity and clear actions. For simple independent values, useState is clearer.
34

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

What are streams in Node.js and what types exist?

Save to ▾
Show answer
Streams process data in chunks instead of loading it all into memory. The four types are Readable (file read, HTTP request), Writable (file write, HTTP response), Duplex (TCP socket) and Transform (gzip, encryption), which modifies data as it passes. Streams handle backpressure, pausing the source when the destination is slow. pipeline() from node:stream/promises connects them safely and handles errors and cleanup.
36

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.

Few big employers listed in Kochi?

Many Kochi candidates also apply to teams in Bangalore and to remote or hybrid roles. Practise the Bangalore set as well.

Frequently asked questions

Which companies hire MERN Stack professionals in Kochi?

Companies with large offices in Kochi include many IT services and product firms. Use their company pages below to practise employer-specific sets.

Are MERN Stack interviews in Kochi different from other cities?

The questions depend more on the company than the city. Kochi's mix of employers decides the style: Testing and data roles are common in its service and product teams

How do I find MERN Stack jobs in Kochi?

Shortlist companies with Kochi offices, keep your CV focused on MERN Stack projects, apply on company career pages and job portals with the Kochi filter, and practise the questions on this page before each interview.