Node.js is a runtime environment that runs JavaScript outside the browser, on the server. It uses the V8 engine (Chrome's engine) and is built on the event-driven, non-blocking I/O model. Node.js uses a single-threaded event loop to handle multiple concurrent connections efficiently. It's ideal for real-time applications, APIs, and data-intensive tasks.
Rate limiting is a technique used to control how many requests a user or client can make to a server within a specific time period. It restricts the number of requests a client can make in a given time window to prevent abuse, improve system stability, and ensure fair usage. Common techniques include: Fixed Window (divide time into buckets, count requests per bucket), Sliding Window (use a time window that slides, more accurate), Token Bucket (refill tokens at fixed rate, allows bursts). Benefits: Prevent DDoS attacks, protect server resources, ensure fair resource allocation. Implement with libraries like express-rate-limit. Return 429 Too Many Requests when limit exceeded. Include rate limit headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset. Use Redis for distributed rate limiting across multiple servers.
CORS is a browser security feature that blocks requests between different origins. When frontend makes a request, browser sends an Origin header. Backend checks if that origin is allowed — if yes, request goes through. We configure this in backend using the CORS middleware.
Middleware is a function that runs between request and response. When a request comes to the server — before it reaches the actual route handler — middleware runs first. It has three parameters — req, res, and next. When middleware finishes its job, it calls next() to move to the next function. Express has built-in middleware like express.json() — it parses the incoming JSON body so req.body becomes accessible. Apart from built-in, custom middleware can be created for specific needs: Auth middleware — checks JWT token before allowing access to protected routes. If token is missing it returns 401. If valid it extracts user data and calls next(). Role middleware — verifies the role of the user. For example, Founder can access everything, HR can access limited routes, Employee can access only their own data. CORS middleware — allows cross origin requests from frontend so browser does not block the API calls.
Browsers block requests between different origins for security (prevent CSRF attacks). CORS lets the backend explicitly allow trusted frontends to access its APIs.
When browser makes cross-origin request, it sends Origin header. Server checks if origin is in allowed list, then responds with Access-Control-Allow-Origin header.
Simple requests (GET, POST) go directly. Complex requests (PUT, DELETE, custom headers) trigger preflight — browser sends OPTIONS request first to check if server allows it.