Ace Your Interviews 🎯
Browse our collection of interview questions across various technologies.
What does MERN stand for and what is each technology's role?
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.
Why is MERN called a full-stack JavaScript stack?
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.
What is MongoDB and how does it differ from MySQL?
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.
What is Mongoose and why use it over the raw MongoDB driver?
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.
What is a REST API and what HTTP methods does it use?
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.
How does React communicate with an Express backend in MERN?
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.
What is CORS and why do MERN developers encounter it?
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' })).
What is JWT and how is it used for authentication in MERN?
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.
What is the purpose of a .env file and why never commit it?
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.
What is the difference between useState and useEffect in React?
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.
Explain the complete request-response cycle in a MERN app.
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.
How do you implement protected routes in React?
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.
What is the Mongoose populate() method?
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.
How do you handle async errors in Express routes?
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.
How do you implement pagination in MERN?
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.
What is an Axios interceptor and why is it useful in MERN?
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.
How do you prevent NoSQL injection in a MERN app?
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.
What is the difference between Mongoose save() and findByIdAndUpdate()?
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.
How do you manage global state in a React MERN frontend?
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.
How do you deploy a MERN app?
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.
How would you architect a MERN app to scale to 100,000 concurrent users?
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.
What is the difference between CSR, SSR, and SSG? Where does MERN fit?
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.
How do you implement real-time features in a MERN app?
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.
What are MongoDB transactions and when are they necessary in MERN?
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.
How do you implement a password reset flow end-to-end in MERN?
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.
What is the N+1 query problem in Mongoose and how do you solve it?
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.
How do you handle file uploads to cloud storage in a production MERN app?
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.
What is React Query and when would you use it in a MERN app?
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.
How would you implement role-based access control (RBAC) across the full MERN stack?
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.
How do you write tests for a full MERN application?
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.