Crack The Job
Express js questions
1. What is [Link]?
Answer: [Link] is a lightweight, flexible [Link] web application framework
used for building web and API servers.
---
2. How do you install Express in a [Link] project?
Answer: Use the command npm install express inside your [Link] project
directory.
---
3. How do you create a basic Express server?
Answer:
const express = require('express');
const app = express();
[Link](3000, () => [Link]('Server running'));
---
4. What is middleware in Express?
Answer: Middleware functions execute during the request-response cycle. They
can modify requests, responses, or terminate the request.
---
5. What are some built-in middlewares in Express 4.x?
Answer: [Link](), [Link](), and [Link]().
---
6. How do you handle routing in Express?
Answer: Use [Link](), [Link](), [Link](), [Link]() to define routes based
on HTTP methods.
---
7. How do you send a JSON response in Express?
Answer: Use [Link]({ key: 'value' }).
---
8. What is the use of [Link]?
Answer: [Link] accesses route parameters in URLs like /users/:id.
---
9. What is the use of [Link]?
Answer: [Link] accesses query string parameters like /search?q=node.
---
10. How do you handle 404 errors in Express?
Answer: Use a middleware at the end of route definitions:
[Link]((req, res) => [Link](404).send('Not Found'));
---
11. How do you handle form data in Express?
Answer: Use [Link]({ extended: true }) to parse URL-encoded form
bodies.
---
12. How do you serve static files using Express?
Answer: Use [Link]([Link]('public')) to serve static files from the public
directory.
---
13. How do you chain route handlers in Express?
Answer: Pass multiple middleware functions to a route, e.g. [Link]('/',
middleware1, middleware2, handler).
---
14. How do you redirect a route in Express?
Answer: Use [Link]('/new-path').
---
15. What is next() in Express?
Answer: next() passes control to the next middleware in the stack.
16. What is the difference between [Link]() and [Link]() in Express?
Answer: [Link]() is used to apply middleware globally or for specific paths.
[Link]() is used to define GET route handlers.
---
17. How do you create a router in [Link]?
Answer:
const express = require('express');
const router = [Link]();
[Link]('/', (req, res) => [Link]('Home'));
[Link] = router;
---
18. How do you import and use routes from another file in Express?
Answer:
const userRoutes = require('./routes/users');
[Link]('/users', userRoutes);
---
19. How do you handle errors in Express using middleware?
Answer: Define error-handling middleware with 4 parameters:
[Link]((err, req, res, next) => {
[Link](err);
[Link](500).send('Server Error');
});
---
20. How do you set custom headers in Express?
Answer: Use [Link]('Header-Name', 'value') or [Link]().
---
21. What is the difference between [Link]() and [Link]()?
Answer: [Link]() can send any type of response; [Link]() sends a JSON
response and sets the content type to application/json.
---
22. What are request lifecycle stages in Express?
Answer: Request → Middleware stack → Route handler → Response → Error
handling (if any).
---
23. How do you limit request rate in Express?
Answer: Use express-rate-limit middleware:
const rateLimit = require('express-rate-limit');
[Link](rateLimit({ windowMs: 1 * 60 * 1000, max: 100 }));
---
24. What is Helmet in Express apps?
Answer: Helmet helps secure Express apps by setting various HTTP headers like
CSP, XSS protection, etc.
---
25. How do you handle cookies in Express?
Answer: Use cookie-parser middleware:
const cookieParser = require('cookie-parser');
[Link](cookieParser());
---
26. How do you store session data in Express?
Answer: Use express-session middleware with optional storage engines like
Redis or MongoDB.
---
27. What are route parameters and how are they used?
Answer: Variables in routes like /users/:id can be accessed via [Link].
---
28. How do you handle file uploads in Express?
Answer: Use multer middleware to handle multipart/form-data.
---
29. What are query parameters and how are they accessed?
Answer: Parameters after ? in a URL. Access them using [Link].
---
30. How do you use environment variables in Express?
Answer: Use the dotenv package and access with [Link].VARIABLE_NAME.
---
31. How do you serve dynamic content with a template engine?
Answer: Use engines like EJS, Pug, or Handlebars:
[Link]('view engine', 'ejs');
[Link]('/', (req, res) => [Link]('index', { name: 'John' }));
---
32. What are chained route handlers?
Answer: Define multiple handlers for a route:
[Link]('/user')
.get((req, res) => [Link]('GET'))
.post((req, res) => [Link]('POST'));
---
33. How can you log requests in Express?
Answer: Use morgan middleware:
const morgan = require('morgan');
[Link](morgan('dev'));
---
34. What is the order of middleware execution?
Answer: Middleware is executed in the order it is defined. Global middleware
runs first, followed by route-specific ones.
---
35. How do you handle JSON body parsing in Express?
Answer: Use [Link]() middleware before route handlers.
36. How do you implement role-based access control (RBAC) in Express?
Answer: Create middleware that checks user roles from the request (e.g.,
[Link]) and conditionally allows access to routes.
---
37. How do you structure a large-scale Express application?
Answer: Organize code into modules (routes, controllers, models, middleware,
config), use dependency injection, and follow MVC or layered architecture.
---
38. What is the purpose of express-async-errors?
Answer: It handles errors from async route handlers without needing try/catch
blocks in each one.
---
39. How can you use Express with TypeScript?
Answer: Install types (@types/express), use .ts files, and define types for
Request, Response, and NextFunction.
---
40. How do you implement global error handling in Express?
Answer: Use a centralized error-handling middleware at the end of the stack
with 4 parameters: (err, req, res, next).
---
41. How do you write unit tests for Express routes?
Answer: Use supertest and jest or mocha to simulate HTTP requests and assert
responses.
---
42. How do you implement logging in a production Express app?
Answer: Use winston or pino for structured logging and store logs in files or
external logging systems.
---
43. What is the use of virtual hosts in Express?
Answer: Virtual hosts allow hosting multiple applications on the same server by
domain name using vhost middleware.
---
44. How do you use clusters in Express to utilize multi-core CPUs?
Answer: Use the [Link] cluster module to spawn multiple worker processes that
share the same port.
---
45. How do you implement caching in Express?
Answer: Use middleware to cache responses (in memory or Redis) or set cache
headers ([Link]('Cache-Control', ...)).
---
46. How do you secure Express apps against XSS and CSRF attacks?
Answer: Use helmet for headers, sanitize input with libraries like xss-clean, and
use csurf middleware for CSRF protection.
---
47. How do you protect an Express API with JWT authentication?
Answer: Verify JWTs in a middleware using jsonwebtoken, extract user info, and
attach it to [Link].
---
48. How do you integrate Express with a frontend (like React)?
Answer: Serve React build files using [Link]() or run frontend and
backend on different ports with CORS handling.
---
49. How do you handle graceful shutdowns in Express?
Answer: Listen for SIGINT/SIGTERM, stop accepting new connections, and close
server/database connections cleanly.
---
50. How do you implement background tasks in Express?
Answer: Use message queues (Bull, RabbitMQ) or setTimeout/setInterval with
caution, preferably offloaded to workers.
---
51. How can Express be used as a GraphQL server?
Answer: Use express-graphql or Apollo Server middleware to create a /graphql
endpoint.
---
52. How do you implement rate limiting per user/IP in Express?
Answer: Use express-rate-limit with keyGenerator to customize limit by IP or
authenticated user.
---
53. How do you load environment-specific configs in Express?
Answer: Use dotenv, and conditionally load .env or config files based on
[Link].NODE_ENV.
---
54. What is content negotiation in Express?
Answer: Based on the Accept header, Express can send different responses
(JSON, HTML, XML) using [Link]().
---
55. How do you implement API versioning in Express?
Answer: Use route prefixes like /api/v1/ and /api/v2/, or version in headers, to
manage multiple API versions.
Best of luck