Ace Your Interviews 🎯

Browse our collection of interview questions across various technologies.

MERN StackBeginner

What does MERN stand for and what is each technology's role?

Answer

MongoDB (document database), Express.js (web framework for Node.js), React (frontend UI library), Node.js (JavaScript server runtime). MongoDB stores data, Express + Node.js build the API, React renders the UI.

MERN StackBeginner

Why is MERN called a full-stack JavaScript stack?

Answer

Because JavaScript runs at every layer — React on the frontend, Node.js and Express on the backend, Mongoose (JS library) communicating with MongoDB. One language, zero context-switching between layers.

MERN StackBeginner

What is MongoDB and how does it differ from MySQL?

Answer

MongoDB is a NoSQL document database storing data as JSON-like BSON documents in collections. MySQL uses tables, rows, and strict schemas with SQL queries. MongoDB is schema-flexible — great for rapidly evolving data structures.

MERN StackBeginner

What is Mongoose and why use it over the raw MongoDB driver?

Answer

Mongoose is an ODM that adds schemas, data validation, middleware hooks (pre/post save), relationship population, and clean query methods on top of MongoDB. The raw driver has none of these — it's just low-level CRUD.

MERN StackBeginner

What is a REST API and what HTTP methods does it use?

Answer

An architectural style for APIs using HTTP. GET (read), POST (create), PUT/PATCH (update), DELETE (remove). URLs represent resources (/users, /products/:id). Data is exchanged as JSON.

MERN StackBeginner

How does React communicate with an Express backend in MERN?

Answer

Through HTTP requests using Axios or fetch. React sends a request to an Express endpoint. Express processes it, queries MongoDB if needed, and returns JSON. React receives the JSON, updates state, and re-renders.

MERN StackBeginner

What is CORS and why do MERN developers encounter it?

Answer

Cross-Origin Resource Sharing — browsers block requests between different origins (localhost:5173 to localhost:5000). Fix with the cors npm package on Express: app.use(cors({ origin: 'http://localhost:5173' })).

MERN StackBeginner

What is JWT and how is it used for authentication in MERN?

Answer

JSON Web Token — a signed token encoding user data. On login, Express creates and returns a JWT. React stores it in localStorage and sends it in Authorization: Bearer <token> headers. Express verifies the signature on protected routes.

MERN StackBeginner

What is the purpose of a .env file and why never commit it?

Answer

Stores sensitive config (DB passwords, JWT secrets) outside the code. Committing exposes these publicly on GitHub — any viewer can access your database. Add .env to .gitignore and set variables in your hosting platform's dashboard.

MERN StackBeginner

What is the difference between useState and useEffect in React?

Answer

useState stores data that triggers a re-render when changed. useEffect runs side effects (API calls, subscriptions) after render. In MERN, you typically fetch data in useEffect and store the result with useState.

MERN StackIntermediate

Explain the complete request-response cycle in a MERN app.

Answer

User action in React → Axios HTTP request → Express receives it → middleware runs (CORS, auth, body parse, validate) → route handler executes → Mongoose queries MongoDB → MongoDB returns docs → Express sends JSON → React updates state → component re-renders.

MERN StackIntermediate

How do you implement protected routes in React?

Answer

Create a ProtectedRoute component that checks auth state from Context or localStorage. If authenticated, render children. If not, use React Router's Navigate component to redirect to /login. Wrap protected pages in this component in route definitions.

MERN StackIntermediate

What is the Mongoose populate() method?

Answer

It replaces an ObjectId reference with the actual referenced document — like a JOIN in SQL. Example: Post.find().populate('author', 'name email') replaces the author ObjectId field with the full User object, but only the name and email fields.

MERN StackIntermediate

How do you handle async errors in Express routes?

Answer

Wrap await calls in try/catch and call next(err) to forward to the centralized 4-parameter error middleware. Or use express-async-errors package to automatically catch thrown async errors without try/catch in every handler.

MERN StackIntermediate

How do you implement pagination in MERN?

Answer

Backend: accept page and limit as query params. Use .skip((page-1)*limit).limit(limit) in Mongoose. Return total document count. Frontend: React tracks current page in state, passes it as Axios query param, renders pagination UI based on total pages from response.

MERN StackIntermediate

What is an Axios interceptor and why is it useful in MERN?

Answer

Middleware for Axios requests and responses. Request interceptor: auto-attach JWT from localStorage to every request's Authorization header. Response interceptor: catch all 401 responses and redirect to /login. Write once, applies globally.

MERN StackIntermediate

How do you prevent NoSQL injection in a MERN app?

Answer

Use mongo-sanitize middleware to strip $ and . from req.body and req.params before Mongoose queries. Mongoose type casting also helps — it converts user input to defined schema types, rejecting unexpected operators.

MERN StackIntermediate

What is the difference between Mongoose save() and findByIdAndUpdate()?

Answer

save() triggers schema validators and all middleware hooks (pre-save — useful for password hashing). findByIdAndUpdate() skips them by default — add { runValidators: true } to enable validation. Use save() when hooks must run.

MERN StackIntermediate

How do you manage global state in a React MERN frontend?

Answer

React Context for infrequent global state (auth user, theme). Zustand for frequently-updating state (cart, filters, notifications) — it's performant and requires no Provider boilerplate. React Query for server state — it handles caching and re-fetching automatically.

MERN StackIntermediate

How do you deploy a MERN app?

Answer

MongoDB Atlas (cloud database, free tier). Railway or Render (Express backend — add env vars in dashboard). Vercel (React frontend — add VITE_API_URL env var). Set CORS origin in Express to your Vercel domain. Test the deployed API with Postman before connecting React.

MERN StackAdvanced

How would you architect a MERN app to scale to 100,000 concurrent users?

Answer

Horizontal scaling — multiple Node.js instances behind a load balancer (NGINX or AWS ALB). Redis for shared session storage and caching across instances. MongoDB Atlas with read replicas. CDN for React static assets. Rate limiting. Bull queues for background jobs. Stateless JWT auth.

MERN StackAdvanced

What is the difference between CSR, SSR, and SSG? Where does MERN fit?

Answer

CSR (MERN default): React renders in the browser — slower first load, faster subsequent navigation. SSR: server sends pre-rendered HTML (Next.js) — better SEO, faster first paint. SSG: HTML at build time — fastest, but static data. MERN is CSR; use Next.js for SSR/SSG benefits with the same stack.

MERN StackAdvanced

How do you implement real-time features in a MERN app?

Answer

Add Socket.io to Express. React connects via socket on mount in useEffect, disconnects on cleanup. Backend emits events on data changes, React listens and updates state. For multi-server horizontal scaling, use socket.io-redis adapter so events propagate across all instances.

MERN StackAdvanced

What are MongoDB transactions and when are they necessary in MERN?

Answer

Transactions ensure multiple operations across collections are atomic — all succeed or all roll back. Required when one business action spans multiple collections: placing an order should atomically reduce inventory AND create the order document. Use Mongoose sessions with startTransaction/commitTransaction.

MERN StackAdvanced

How do you implement a password reset flow end-to-end in MERN?

Answer

User requests reset → Express generates random token, hashes it, stores with 10-min expiry in User document, emails raw token via Nodemailer. User clicks link → React sends token to backend → Express hashes received token, compares with stored hash, checks expiry, if valid updates password and clears reset fields.

MERN StackAdvanced

What is the N+1 query problem in Mongoose and how do you solve it?

Answer

Fetching N documents then running a separate query per document for related data — N+1 total queries. Fix with populate() (single $lookup under the hood) or manually batch with $in — fetch all related IDs in one query, join in JavaScript.

MERN StackAdvanced

How do you handle file uploads to cloud storage in a production MERN app?

Answer

Multer with memoryStorage on Express — file goes to buffer, not disk. Stream the buffer to Cloudinary (cloudinary.uploader.upload_stream) or AWS S3 (PutObjectCommand with buffer). Store returned URL in MongoDB. Never save to server disk — containers are stateless and disks fill up.

MERN StackAdvanced

What is React Query and when would you use it in a MERN app?

Answer

TanStack Query manages server state — caching, background refetching, stale-while-revalidate, pagination, optimistic updates — automatically. useEffect + useState manages all this manually. For any MERN app beyond a tutorial, React Query reduces data-fetching code by 60–70% and eliminates most loading/error state bugs.

MERN StackAdvanced

How would you implement role-based access control (RBAC) across the full MERN stack?

Answer

Backend: User model has a role field (user/admin/seller). protect middleware attaches req.user. Role-checking middleware (adminOnly, sellerOnly) compares req.user.role. Frontend: AuthContext exposes user.role. React renders different UI or blocks navigation based on role. Never trust frontend role checks alone — backend must enforce.

MERN StackAdvanced

How do you write tests for a full MERN application?

Answer

Backend: Jest + Supertest — make real HTTP requests against Express with a test MongoDB database. Mock external services (email, payment). Frontend: React Testing Library + MSW (Mock Service Worker) to intercept API calls and return mock data. E2E: Playwright simulates full user journeys across both layers.

Ready for a real challenge?

Master MERN Stack