Skip to content

HCLTech MERN Stack Interview Questions & Answers

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

About HCLTech hiring for MERN Stack roles

HCLTech is an Indian multinational IT services and consulting company providing digital engineering, cloud, infrastructure, software products and data services. It works with clients in sectors such as financial services, manufacturing, life sciences and telecom. In India it hires for software engineers, test engineers, data analysts and data engineers through campus drives and programmes like TechBee.

For MERN Stack roles, this HCLTech practice set focuses most on Authentication and Security (6), React Fundamentals (6), React Hooks, State and Performance (5), MongoDB and Mongoose (4). It has 12 easy, 17 medium, 1 hard questions, so you can start easy and work up to the harder ones.

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

HCLTech MERN Stack interview process

  1. Online assessment (aptitude + technical)
  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 HCLTechStart 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

Write basic CRUD commands in mongosh for a users collection.

Save to ▾
Show answer
Core shell commands: db.users.insertOne({ name: 'Riya', email: 'riya@mail.com', age: 24 }) db.users.find({ age: { $gte: 21 } }, { name: 1, email: 1, _id: 0 }) db.users.updateOne({ email: 'riya@mail.com' }, { $set: { age: 25 } }) db.users.deleteMany({ isActive: false }) db.users.countDocuments({ city: 'Pune' }) The second argument of find is a projection that controls which fields are returned.
02

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

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

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

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

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

What is the difference between controlled and uncontrolled components?

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

Some tests pass locally but fail randomly in CI. How do you handle flaky tests?

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

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

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

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

Describe a production issue you handled in a Node.js service.

Save to ▾
Show answer
Situation: our order API started timing out every evening at peak. Task: as the on-call developer I had to restore it. Action: I checked logs and metrics, found event-loop lag spikes, and traced them to a synchronous CSV export running inside a request. I moved the export to a background job and added event-loop lag alerts. Result: p95 latency dropped from 4 seconds to 300 ms and timeouts stopped.
13

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

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

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

Users can upload profile pictures and documents. What security measures do you put in place?

Save to ▾
Show answer
Enforce size limits and an allowlist of types, checking magic bytes rather than trusting the extension or Content-Type. Rename files with random ids, store them in object storage outside the web root, and serve them from a separate domain or with Content-Disposition attachment for documents. Strip image metadata, scan for malware where needed, use pre-signed URLs with expiry for private files, and never execute or include uploaded files.
17

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

A client wants deleted records to be recoverable. How would you implement soft delete with Mongoose?

Save to ▾
Show answer
Add fields like isDeleted: Boolean with default false and deletedAt: Date. The delete endpoint sets these instead of removing the document. Add a pre-find query middleware that filters isDeleted: false by default, and an admin route to restore. Include isDeleted in relevant indexes or use partial indexes, for example a unique email index that only applies to non-deleted users. Purge old records with a scheduled job.
19

Write a docker-compose file to run a MERN app locally.

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

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

Explain the core ideas of Redux Toolkit.

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

Write a React Testing Library test for a counter button.

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

What is a custom hook and what rules must hooks follow?

Save to ▾
Show answer
A custom hook is a function whose name starts with use and that calls other hooks to package reusable stateful logic, such as useFetch, useDebounce or useAuth. Each component using it gets its own state. Hooks must be called at the top level of a component or another hook, never inside conditions, loops or nested functions, so React can match state by call order. The eslint-plugin-react-hooks rules enforce this.
24

What are the main uses of useRef?

Save to ▾
Show answer
useRef returns a mutable object whose current property persists across renders without causing a re-render when changed. It is used to access DOM nodes, for example focusing an input or measuring size, and to store values like timer ids, previous values or the latest callback. Do not read or write ref.current during rendering for values that affect output, because React will not re-render when it changes.
25

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

What is the difference between useMemo and useCallback?

Save to ▾
Show answer
useMemo caches the result of a calculation, recomputing only when dependencies change, for example a filtered and sorted list. useCallback caches a function reference, so useCallback(fn, deps) equals useMemo(() => fn, deps). They help when passing values or callbacks to memoized children or as effect dependencies. They have their own cost, so do not wrap everything; the React Compiler can now add this memoization automatically.
27

Why does React need keys in lists, and why is using the array index risky?

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

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

What is the difference between authentication and authorization?

Save to ▾
Show answer
Authentication verifies who the user is, for example by checking email and password, an OTP or a Google login, and results in a session or token. Authorization decides what that authenticated user may do, such as whether a normal user can delete products or only an admin can. Failed authentication should return 401 Unauthorized, while an authenticated user lacking permission should get 403 Forbidden.
30

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.

Tips to crack the HCLTech MERN Stack interview

  • Revise programming basics, SQL and networking fundamentals, as HCLTech roles span applications and infrastructure services.
  • Learn about HCLTech's software products business, HCLSoftware, and its engineering and R&D services.
  • Be clear and honest about your preferred domain and shift flexibility, as some roles involve support or global time zones.
  • 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; HCLTech interviewers usually ask follow-ups on your first answer.

Frequently asked questions

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

Candidates usually go through 4 stages: Online assessment (aptitude + technical); 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 HCLTech MERN Stack interview?

This practice set leans on Authentication and Security (6), React Fundamentals (6), React Hooks, State and Performance (5), MongoDB and Mongoose (4). Revise those first, then practise explaining one or two of your own projects end to end, because most HCLTech interviewers ask you to walk through real work.

Are these the exact questions asked at HCLTech?

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

Where does HCLTech hire MERN Stack professionals in India?

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

MERN Stack questions for similar companies