20 Full Stack Interview Questions
Click any question to expand the detailed answer. These cover the most frequently tested full stack, backend, and systems concepts in engineering interviews.
REST (Representational State Transfer) is an architectural style for designing networked applications. It was defined by Roy Fielding in 2000. A web API is called "RESTful" when it follows REST's six architectural constraints:
- Client-Server: The UI (client) and data storage (server) are separated. They evolve independently.
- Stateless: Each request contains all the information needed to process it. The server stores no session state between requests (auth is sent with every request, typically via a JWT in the Authorization header).
- Cacheable: Responses must indicate whether they can be cached. Caching reduces load and improves performance.
- Uniform Interface: Resources are identified by URLs. Interactions use standard HTTP methods (GET, POST, PUT, PATCH, DELETE). Responses include self-descriptive messages (Content-Type headers, links to related resources).
- Layered System: The client doesn't need to know if it's talking directly to the server or through proxies/load balancers.
- Code on Demand (optional): Servers can send executable code to clients (e.g., JavaScript).
// RESTful URL design β nouns, not verbs
GET /products β list all products
GET /products/42 β get product 42
POST /products β create a new product
PUT /products/42 β replace product 42 entirely
PATCH /products/42 β update product 42 partially
DELETE /products/42 β delete product 42
// NOT RESTful
GET /getProduct?id=42
POST /createNewProduct
GET /deleteProduct/42
Both update a resource, but they differ in scope:
- PUT β replaces the entire resource. If you omit a field, it is removed (or reset to its default). It is idempotent: calling it multiple times with the same body always produces the same result.
- PATCH β applies a partial update. Only the fields you include in the request body are changed. Other fields remain untouched.
// Existing user: { id: 1, name: "Sai", email: "sai@x.com", role: "admin" }
// PUT /users/1 β must send FULL representation
PUT /users/1
Body: { name: "Sai Kumar", email: "sai@x.com", role: "admin" }
// If role is omitted, it will be cleared or default to null
// PATCH /users/1 β only what changes
PATCH /users/1
Body: { name: "Sai Kumar" }
// email and role stay as-is β only name is updated
// In Express:
app.put('/users/:id', async (req, res) => {
const user = await User.findByIdAndReplace(req.params.id, req.body);
res.json(user);
});
app.patch('/users/:id', async (req, res) => {
const user = await User.findByIdAndUpdate(
req.params.id, req.body, { new: true }
);
res.json(user);
});
In practice: Most real-world APIs use PATCH for user-facing updates (change your display name, update a setting). PUT is more common for replacing a complete resource like uploading a file.
A JWT (JSON Web Token) is a compact, self-contained token that encodes user claims and is cryptographically signed. It enables stateless authentication β the server doesn't need a session store.
Structure: header.payload.signature (Base64URL-encoded)
// Header: { "alg": "HS256", "typ": "JWT" }
// Payload: { "userId": 42, "role": "admin", "exp": 1716000000 }
// Signature: HMACSHA256(base64(header) + "." + base64(payload), SECRET_KEY)
// Full flow:
// 1. Login β client sends credentials
POST /auth/login
Body: { email: "sai@x.com", password: "password123" }
// 2. Server verifies, creates token
const token = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '24h' }
);
res.json({ token });
// 3. Client stores token (localStorage or httpOnly cookie)
// Sends it with every subsequent request
GET /api/orders
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
// 4. Server validates on every request (middleware)
function authMiddleware(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token' });
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded; // attach user info to request
next();
} catch {
res.status(401).json({ error: 'Invalid or expired token' });
}
}
Security notes: Store JWTs in httpOnly cookies (not localStorage) to prevent XSS. Use short expiry (15minβ24h) + refresh tokens. Never put sensitive data (passwords, credit cards) in the payload β it is only encoded, not encrypted.
These two terms are often confused but represent distinct security concerns:
- Authentication (AuthN) β Who are you? Verifying the identity of a user. Methods: username/password, OAuth, biometrics, magic links, MFA.
- Authorization (AuthZ) β What are you allowed to do? Checking permissions after identity is established. Methods: roles (RBAC), permissions, ownership checks.
// Authentication β verify identity, issue token
app.post('/login', async (req, res) => {
const user = await User.findOne({ email: req.body.email });
if (!user || !await bcrypt.compare(req.body.password, user.password)) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = jwt.sign({ userId: user.id, role: user.role }, SECRET);
res.json({ token });
});
// Authorization β check permissions on a route
// Middleware: require authentication
app.use('/api', authMiddleware); // all /api routes need a valid token
// Middleware: require specific role
function requireRole(role) {
return (req, res, next) => {
if (req.user.role !== role) {
return res.status(403).json({ error: 'Forbidden β insufficient role' });
}
next();
};
}
app.delete('/api/products/:id', requireRole('admin'), deleteProduct);
// 401 Unauthorized β authentication failed (not logged in)
// 403 Forbidden β authorization failed (logged in, but no permission)
Memory trick: Authentication = proving you're who you say you are. Authorization = proving you're allowed to do what you're trying to do.
The critical distinction is reversibility:
- Encryption is reversible β given the key, you can decrypt back to the original. If an attacker steals the database AND the key, they have all passwords in plaintext.
- Hashing is a one-way function β you cannot recover the original password from the hash. The server never needs to know the actual password; it only needs to verify that what you entered hashes to the same value.
const bcrypt = require('bcrypt');
// NEVER store plaintext: user.password = "password123"
// NEVER encrypt: user.password = encrypt("password123", key)
// CORRECT β hash with bcrypt (slow, intentionally)
async function register(email, plainPassword) {
const saltRounds = 12; // higher = slower = harder to brute-force
const hashed = await bcrypt.hash(plainPassword, saltRounds);
await User.create({ email, password: hashed });
}
// Verify at login β no decryption, just re-hash and compare
async function login(email, plainPassword) {
const user = await User.findOne({ email });
const match = await bcrypt.compare(plainPassword, user.password);
// bcrypt.compare handles the salt internally
return match;
}
Why bcrypt (not SHA256)? bcrypt is deliberately slow and includes a salt to prevent rainbow table attacks. General-purpose hash functions like SHA256 are too fast β attackers can test billions of guesses per second. Use bcrypt, Argon2, or scrypt for passwords.
SQL injection is an attack where malicious SQL code is inserted into a query through user input, allowing an attacker to read, modify, or delete data they shouldn't have access to β or even execute admin operations on the database.
// VULNERABLE β string interpolation
const query = `SELECT * FROM users WHERE email = '${req.body.email}'`;
// Attacker inputs: ' OR '1'='1
// Query becomes: SELECT * FROM users WHERE email = '' OR '1'='1'
// β returns ALL users in the database!
// Even worse input: '; DROP TABLE users; --
// Query: SELECT * FROM users WHERE email = ''; DROP TABLE users; --'
// β deletes the entire users table
Prevention β always use parameterized queries / prepared statements:
// SAFE β parameterized query (pg node library)
const result = await pool.query(
'SELECT * FROM users WHERE email = $1',
[req.body.email] // value is passed separately, never interpolated
);
// SAFE β with mysql2
const [rows] = await pool.execute(
'SELECT * FROM users WHERE email = ?',
[req.body.email]
);
// SAFE β with an ORM (Sequelize, Prisma)
const user = await User.findOne({ where: { email: req.body.email } });
// ORM handles parameterization automatically
Additional defenses: Validate and sanitize all input, use the least-privileged database user for your app, and never display raw database errors to end users.
An ORM (Object-Relational Mapper) is a library that maps database tables to programming language objects and lets you query and manipulate data using the language's syntax instead of writing raw SQL.
// Raw SQL
const result = await pool.query(
`SELECT o.id, o.total, u.name
FROM orders o
JOIN users u ON o.user_id = u.id
WHERE o.status = $1`,
['pending']
);
// Prisma ORM β same query, TypeScript-safe
const orders = await prisma.order.findMany({
where: { status: 'pending' },
include: { user: { select: { name: true } } },
});
// Sequelize ORM
const orders = await Order.findAll({
where: { status: 'pending' },
include: [{ model: User, attributes: ['name'] }],
});
Pros:
- Less boilerplate, faster development.
- Type safety (Prisma has excellent TypeScript integration).
- Database migrations managed in code.
- Automatic parameterization prevents SQL injection.
- Easier to switch databases (abstracting away DB-specific syntax).
Cons:
- Can generate inefficient queries for complex operations.
- Adds a learning curve on top of SQL.
- Heavy abstraction can hide performance problems.
- Complex joins or aggregations are sometimes clearer in raw SQL.
A database index is a data structure (typically a B-tree) that allows the database to find rows matching a WHERE condition without scanning every row in the table. Think of it like a book's index β instead of reading every page, you jump directly to what you need.
-- Without index: full table scan (O(n))
-- With index on email: B-tree lookup (O(log n))
-- Create an index
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_orders_user_status ON orders(user_id, status); -- composite
-- Check if a query uses an index (PostgreSQL)
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'sai@x.com';
-- "Index Scan using idx_users_email on users" β index is used β
-- Tradeoffs
-- Reads: dramatically faster (especially for large tables)
-- Writes: slightly slower (INSERT/UPDATE/DELETE must update the index)
-- Storage: index occupies additional disk space
When to add an index:
- Columns frequently used in
WHEREclauses. - Foreign keys (joins).
- Columns used in
ORDER BY/GROUP BY.
When NOT to index: Small tables (full scan is fine), columns with very few distinct values (e.g., a boolean column β a full scan is often faster), tables with very high write volume where index maintenance overhead matters.
Connection pooling is the practice of maintaining a set of reusable database connections. Opening a new database connection for every request is expensive (TCP handshake, auth, setup). A pool creates a fixed number of connections at startup and reuses them.
// Without pooling β opens/closes connection per request
app.get('/products', async (req, res) => {
const conn = await openConnection(); // expensive!
const rows = await conn.query('SELECT * FROM products');
await conn.close(); // wasted
res.json(rows);
});
// With connection pool (pg library)
const { Pool } = require('pg');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 20, // max 20 connections in pool
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
// Pool manages connections automatically
app.get('/products', async (req, res) => {
const { rows } = await pool.query('SELECT * FROM products');
// pool.query: borrows a connection, runs query, returns connection to pool
res.json(rows);
});
// Prisma uses its own pool internally
// Configure via DATABASE_URL connection limit: ?connection_limit=10
Sizing the pool: A common formula is 2 * CPU cores + 1. Too small β requests wait. Too large β the database is overwhelmed by concurrent connections. In serverless environments (Vercel, Netlify), use PgBouncer or a connection pooler like Supabase's built-in pooler.
These are three approaches to rendering web pages, each with different performance and SEO tradeoffs:
- CSR (Client-Side Rendering): The browser receives an almost-empty HTML shell and a JS bundle. React runs in the browser, fetches data, and builds the page. Initial load is slow (blank screen until JS loads + data fetches). Not ideal for SEO by default. Used in: standard React SPAs (Create React App).
- SSR (Server-Side Rendering): The server renders the full HTML on every request and sends it to the browser. Faster initial paint, great SEO. The browser then "hydrates" β attaches React's event handlers to the server-rendered HTML. Used in: Next.js
getServerSideProps. Best for personalized, real-time pages (user dashboards, search results). - SSG (Static Site Generation): HTML is pre-built at build time and served as static files (from a CDN). Fastest possible delivery, best SEO. Used in: Next.js
getStaticProps, Gatsby. Best for content that doesn't change per-user or changes infrequently (blogs, marketing pages, documentation).
// Next.js β choose per page
// SSG β rendered at build time
export async function getStaticProps() {
const products = await fetchAllProducts();
return { props: { products }, revalidate: 60 }; // ISR: regenerate every 60s
}
// SSR β rendered at request time
export async function getServerSideProps(context) {
const user = await getUser(context.req.cookies.token);
const orders = await getOrdersForUser(user.id);
return { props: { orders } };
}
// CSR β fetch in useEffect (no special Next.js function)
useEffect(() => { fetch('/api/cart').then(...) }, []);
Environment variables are key-value pairs stored outside your code that configure application behavior for different environments (development, staging, production). They keep secrets out of source code and let the same codebase run differently in each environment.
# .env file (NEVER commit to git)
DATABASE_URL=postgresql://user:password@localhost:5432/myapp
JWT_SECRET=super-secret-key-minimum-32-characters
STRIPE_SECRET_KEY=sk_live_xxxxxxxxxxxx
NODE_ENV=development
# Access in Node.js
const dbUrl = process.env.DATABASE_URL;
const jwtSecret = process.env.JWT_SECRET;
# .gitignore must include:
.env
.env.local
.env.production
Why they matter:
- Security: Secrets never appear in version history. If you commit a secret, rotate it immediately β git history is permanent.
- Flexibility: Point to a local DB in development, a real DB in production β without code changes.
- 12-Factor App principle: Configuration that varies between environments should come from environment variables, not from code.
In production (Vercel, Railway, Heroku, AWS), set env vars through the platform's dashboard or secrets manager β never via .env files checked into git.
CORS (Cross-Origin Resource Sharing) is a browser mechanism that controls which origins are allowed to make requests to your server. Browsers enforce the Same-Origin Policy by default, blocking cross-origin requests unless the server explicitly allows them via CORS headers.
An "origin" is the combination of protocol + hostname + port: http://localhost:3000 and http://localhost:5000 are different origins.
// Express β using the cors package
const cors = require('cors');
// Allow a single origin
app.use(cors({ origin: 'https://myapp.com' }));
// Allow multiple origins
const allowedOrigins = ['https://myapp.com', 'https://staging.myapp.com'];
app.use(cors({
origin: function(origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true, // allow cookies / Authorization headers
}));
// Manual headers (without the cors package)
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'https://myapp.com');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') return res.sendStatus(200); // preflight
next();
});
Common mistake: Using origin: '*' (allow all) with credentials: true β this is explicitly disallowed by the spec. You must specify an exact origin when using credentials.
Middleware in Express is a function that has access to the request (req), response (res), and the next function. Middleware functions execute in a pipeline β each one can process the request, modify res/req, and either end the request or pass it to the next function with next().
// Middleware signature
function myMiddleware(req, res, next) {
// do something with req/res
next(); // pass control to next middleware or route handler
// OR: res.json(...) to end the request cycle
}
// Request pipeline for: POST /api/orders
// β cors() β add CORS headers
// β express.json() β parse JSON body into req.body
// β authMiddleware β verify JWT, attach req.user
// β requireRole() β check user role
// β route handler β execute business logic, send response
// Real examples:
app.use(cors()); // global
app.use(express.json()); // parse JSON bodies
app.use(morgan('dev')); // request logging
// Per-route middleware
app.get('/api/profile', authMiddleware, async (req, res) => {
const user = await User.findById(req.user.id);
res.json(user);
});
// Error-handling middleware β 4 args
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: err.message });
});
The middleware pattern makes Express extremely composable β you build complex pipelines from small, single-responsibility functions. This is the core design pattern of Express applications.
HTTP status codes communicate the outcome of a request. They are grouped by their first digit:
- 2xx β Success
200 OKβ Request succeeded. Used for GET, PUT, PATCH, DELETE responses.201 Createdβ Resource was successfully created. Used after POST creates a new record. Should include aLocationheader pointing to the new resource.204 No Contentβ Success with no response body. Common for DELETE.- 4xx β Client errors (the request is wrong)
400 Bad Requestβ Invalid request syntax, missing required fields, validation error.401 Unauthorizedβ Authentication required or failed (no token, expired token).403 Forbiddenβ Authenticated, but not authorized (wrong role, not the resource owner).404 Not Foundβ Resource doesn't exist at this URL.409 Conflictβ Resource already exists (e.g., registering with a duplicate email).422 Unprocessable Entityβ Request was well-formed but failed semantic validation.- 5xx β Server errors (server failed to fulfill a valid request)
500 Internal Server Errorβ Unexpected server failure. Generic catch-all.502 Bad Gatewayβ Upstream server returned an invalid response.503 Service Unavailableβ Server temporarily overloaded or down for maintenance.
// Use correct status codes in Express
res.status(201).json({ id: newUser.id, email: newUser.email });
res.status(400).json({ error: 'Email is required' });
res.status(401).json({ error: 'Invalid token' });
res.status(403).json({ error: 'Admin access required' });
res.status(404).json({ error: 'Product not found' });
Pagination is the practice of returning a subset of results per request rather than the entire dataset. Without pagination, an API endpoint that returns all products from a million-row table would crush your database, server memory, and network bandwidth.
// Offset pagination (simple, most common)
GET /api/products?page=2&limit=20
// Express + SQL implementation
app.get('/api/products', async (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 20;
const offset = (page - 1) * limit;
const { rows: products } = await pool.query(
'SELECT * FROM products ORDER BY id LIMIT $1 OFFSET $2',
[limit, offset]
);
const { rows: [{ count }] } = await pool.query(
'SELECT COUNT(*) FROM products'
);
res.json({
data: products,
pagination: {
page, limit,
total: parseInt(count),
totalPages: Math.ceil(count / limit),
hasNext: page * limit < count,
}
});
});
// Cursor pagination (better for large/real-time datasets)
GET /api/products?cursor=eyJpZCI6MTAwfQ&limit=20
// "Give me 20 products after the cursor position"
// Stable even if rows are inserted/deleted between pages
Offset pagination tradeoff: Simple to implement but can return inconsistent results if data changes between pages (a row deleted causes the next page to skip one item). Use cursor-based pagination for feeds, timelines, and real-time data.
These are two architectural approaches to structuring a backend application.
Monolith: The entire application (auth, orders, products, payments, notifications) is a single deployable unit. One codebase, one database, one deployment. Simpler to develop and debug at small scale. The risk: as it grows, it becomes harder to deploy, scale specific parts, or use different technologies for different features.
Microservices: The application is split into small, independent services, each responsible for one business domain. Services communicate via APIs (HTTP/REST, gRPC) or message queues (RabbitMQ, Kafka). Each service can be deployed, scaled, and developed independently.
// Monolith β one Express app handles everything
app.use('/auth', authRouter);
app.use('/products', productRouter);
app.use('/orders', orderRouter);
app.use('/payments', paymentRouter);
// One process, one database, deployed together
// Microservices β separate processes
// auth-service: http://auth:3001
// product-service: http://products:3002
// order-service: http://orders:3003 (calls product-service for data)
// payment-service: http://payments:3004
// api-gateway: http://api:80 (routes requests to services)
// Order service calling product service
const product = await fetch('http://products:3002/api/products/' + id);
Reality: Most startups and small teams should start with a monolith. Microservices add significant operational complexity (service discovery, distributed tracing, eventual consistency). Companies like Amazon and Netflix moved to microservices after their monoliths became too large to manage β not before.
CI/CD (Continuous Integration / Continuous Deployment) is the practice of automating the process of testing and deploying code changes.
- Continuous Integration (CI): Every code push automatically triggers a build and test suite. If tests fail, the team is notified before the code reaches production. Catches bugs early, keeps the main branch always in a releasable state.
- Continuous Delivery (CD): After CI passes, the code is automatically deployed to a staging environment. Deployment to production requires manual approval.
- Continuous Deployment: Every change that passes CI is automatically deployed to production with no manual step.
# GitHub Actions CI/CD pipeline (.github/workflows/ci.yml)
name: CI/CD Pipeline
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with: { node-version: '20' }
- run: npm ci
- run: npm test
- run: npm run build
deploy:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v3
- run: npm ci && npm run build
- name: Deploy to Vercel
run: npx vercel --prod --token=${{ secrets.VERCEL_TOKEN }}
Popular CI/CD tools: GitHub Actions (most common), GitLab CI, CircleCI, Jenkins. Platforms like Vercel and Railway handle deployment automatically from GitHub pushes.
A CDN (Content Delivery Network) is a geographically distributed network of servers (edge nodes) that cache and deliver content to users from the server closest to them, reducing latency.
Without a CDN: A user in Nairobi requesting assets from a server in New York experiences ~200ms round-trip latency.
With a CDN: Nairobi's request is served from an edge node in Johannesburg (~20ms). The HTML, JS, CSS, and images are cached there after the first request.
// What a CDN caches:
// - Static assets: JS bundles, CSS, images, fonts
// - HTML (for SSG sites β this is the core of Vercel/Netlify's CDN)
// - API responses (with cache-control headers)
// Cache-Control headers tell the CDN what to cache
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
// β cache for 1 year, immutable (file content won't change, uses hashed filenames)
res.setHeader('Cache-Control', 'no-cache, no-store');
// β don't cache (for personalized/sensitive data)
// Popular CDNs:
// Cloudflare, AWS CloudFront, Vercel Edge Network, Fastly, Akamai
// In Next.js β SSG pages are automatically edge-cached by Vercel
// All assets in /public are served through the CDN
Benefits: Lower latency for global users, reduced load on your origin server, higher availability (CDN absorbs traffic spikes), built-in DDoS mitigation at scale.
HTTP and WebSockets are both protocols built on TCP, but they differ in how they handle communication:
- HTTP: Request-response. Client sends a request, server responds, connection closes (or is reused for the next request). The server cannot push data to the client without being asked. Good for: REST APIs, page loads, one-off data fetches.
- WebSockets: Full-duplex, persistent connection. After an initial HTTP handshake (upgrade), a single TCP connection stays open and both sides can send messages at any time. No request-response cycle. Good for: real-time chat, live notifications, collaborative editing, live dashboards, online games.
// WebSocket server (Node.js with ws library)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (message) => {
// Broadcast to all connected clients
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.on('close', () => console.log('Client disconnected'));
});
// WebSocket client (browser)
const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = (event) => console.log('Received:', event.data);
ws.send('Hello from client!');
// Socket.io adds rooms, namespaces, auto-reconnect on top of WebSockets
When to use each: Polling (repeated HTTP requests) is fine for data that updates every 30+ seconds. WebSockets shine when you need sub-second updates or server-initiated messages.
A production API needs multiple layers of security β no single measure is sufficient on its own:
- Authentication & Authorization: Require JWTs or API keys on all non-public endpoints. Validate tokens on every request. Enforce role-based access control (RBAC). Return 401/403 with clear messages.
- HTTPS / TLS everywhere: Never accept or respond over plain HTTP in production. Use TLS 1.2+. Enforce with HSTS headers (
Strict-Transport-Security). Platforms like Vercel, Railway, and Render handle this automatically. - Input validation & sanitization: Validate all user input (type, length, format) before using it. Use libraries like
zodorjoi. Never interpolate user data into SQL (parameterized queries). - Rate limiting: Limit requests per IP/user to prevent brute-force attacks, credential stuffing, and DoS. Tools:
express-rate-limit, Cloudflare rate limiting. - Security headers: Set HTTP headers that instruct browsers to block common attacks:
Content-Security-Policyβ prevent XSSX-Content-Type-Options: nosniffβ prevent MIME sniffingX-Frame-Options: DENYβ prevent clickjacking- Use
helmetin Express to set all of these automatically.
- CORS configured correctly: Only allow your frontend origins. Don't use
origin: '*'with credentials. - Secrets management: All secrets in environment variables, never in source code. Rotate keys regularly. Use a secrets manager (AWS Secrets Manager, HashiCorp Vault) in production.
- Logging & monitoring: Log all authentication events (successes, failures, lockouts). Alert on anomalies. Tools: Datadog, Sentry, Logtail.
// Quick Express security setup
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
app.use(helmet()); // security headers
app.use(cors({ origin: process.env.ALLOWED_ORIGIN, credentials: true }));
app.use(express.json({ limit: '10kb' })); // prevent large payload attacks
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });
app.use('/api/', limiter);
Ready to land a full stack role?
Ramayai trains you end-to-end β frontend to deployment.
Join the Best AI Programs β three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses β