Node.js & Express.js

Node.js & Express.js​ Interview Questions and Answers

Section 1: Core Node.js Concepts (20+ Questions)

1. What is the event loop in Node.js?
The event loop is the mechanism that allows Node.js to perform non-blocking I/O operations by offloading operations to the system kernel. It continuously checks the call stack and callback queue and processes tasks asynchronously.

2. Explain the difference between process.nextTick(), setImmediate(), and setTimeout().

  • process.nextTick(): Executes a callback after the current operation.

  • setImmediate(): Executes after I/O events.

  • setTimeout(): Executes after a specified delay.

process.nextTick(() => console.log('nextTick'));
setImmediate(() => console.log('setImmediate'));
setTimeout(() => console.log('setTimeout'), 0);

3. What are streams in Node.js?
Streams are abstract interfaces for working with streaming data in Node.js. Types include:

  • Readable

  • Writable

  • Duplex

  • Transform

4. How does Node.js handle child processes?
Using child_process module: spawn, exec, fork, execFile.

const { exec } = require('child_process');
exec('ls -la', (err, stdout, stderr) => {
  if (err) throw err;
  console.log(stdout);
});

5. What is the purpose of the cluster module?
To utilize multi-core systems by spawning worker processes that share the same server port.

6. What is the difference between require and import in Node.js?

  • require is CommonJS.

  • import is ES6 Module. Use "type": "module" in package.json to enable.

7. What is a memory leak and how do you prevent it in Node.js?
Unintended memory retention. Use tools like heapdump, v8-profiler, and monitor global variables.

8. Explain the Buffer class in Node.js.
Buffer handles binary data.

const buf = Buffer.from('Hello');
console.log(buf.toString()); // Hello

9. How does Node.js handle errors?
Through error-first callbacks, try/catch in async/await, or .catch() with promises.

10. What are the different types of timers in Node.js?

  • setTimeout()

  • setInterval()

  • setImmediate()

11. What is the purpose of global in Node.js?
It's the global namespace object, similar to window in browsers.

12. Explain the role of V8 in Node.js.
V8 is the JavaScript engine by Google. Node.js uses it to compile JS to machine code.

13. How do you manage asynchronous operations in Node.js?
Using callbacks, promises, or async/await.

14. What is middleware in context of Node.js?
Functions that execute during the request-response cycle. In Express, used to modify req, res, or finish the cycle.

15. How to handle uncaught exceptions in Node.js?

process.on('uncaughtException', (err) => {
  console.error('Caught exception:', err);
});

16. What is the REPL in Node.js?
Read-Eval-Print Loop: interactive shell to test JS/Node expressions.

17. Explain the difference between synchronous and asynchronous methods.
Synchronous blocks the event loop. Asynchronous allows other code to run.

18. What is a callback hell and how to avoid it?
Nested callbacks make code hard to read. Avoid with promises/async-await.

19. What are worker threads?
Allow running JS in parallel on multiple threads.

const { Worker } = require('worker_threads');

20. What is the difference between fork() and spawn()?

  • spawn() runs a command.

  • fork() creates a new Node.js process and enables communication via IPC.

21. What tools can you use to debug Node.js applications?
node --inspect, Chrome DevTools, ndb, console.log, VS Code debugger.


Section 2: Express.js Core Concepts (20+ Questions)

1. What is Express.js?
A fast, unopinionated, minimalist web framework for Node.js that simplifies routing, middleware, and server management.

2. How do you set up a basic Express server?

const express = require('express');
const app = express();

app.get('/', (req, res) => res.send('Hello World'));

app.listen(3000, () => console.log('Server running'));

3. What are middleware functions in Express?
Functions that execute during the lifecycle of a request to the server. They have access to req, res, and next().

4. What is the difference between application-level and router-level middleware?

  • Application-level applies to entire app.

  • Router-level applies to specific router instance.

5. What is the use of next() in Express?
Passes control to the next middleware function.

6. How do you handle 404 errors in Express?
Define middleware at the end:

app.use((req, res) => res.status(404).send('Not Found'));

7. How do you handle errors globally in Express?
Error-handling middleware has 4 arguments:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

8. How do you parse incoming JSON requests in Express?
Use built-in middleware:

app.use(express.json());

9. What are route parameters in Express?
Variables in URL:

app.get('/user/:id', (req, res) => res.send(req.params.id));

10. What is the purpose of express.Router()?
Modular way to organize routes in different files.

11. How can you serve static files with Express?

app.use(express.static('public'));

12. How do you implement CORS in Express?
Use cors middleware:

const cors = require('cors');
app.use(cors());

13. How to handle file uploads in Express?
Use multer middleware:

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => res.send('Uploaded'));

14. How do you protect routes in Express?
Add middleware to check authentication before proceeding.

15. What is a query parameter and how is it accessed?
Parameters in the URL after ?. Accessed via req.query.

app.get('/search', (req, res) => res.send(req.query.q));

16. How do you redirect a request in Express?

res.redirect('/new-url');

17. What are the HTTP methods supported by Express?
GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD

18. How to implement custom middleware in Express?

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

19. How do you chain route handlers in Express?

app.get('/example', middleware1, middleware2, (req, res) => res.send('Done'));

20. How to use async/await in Express routes?
Wrap async functions in try/catch:

app.get('/', async (req, res) => {
  try {
    const data = await someAsyncCall();
    res.send(data);
  } catch (err) {
    res.status(500).send(err.message);
  }
});

21. How do you handle nested routes using Express Router?

const router = express.Router();
router.get('/profile', (req, res) => res.send('Profile'));
app.use('/user', router); // /user/profile

Section 3: Advanced Node.js Patterns & Performance Optimization (20+ Questions)

1. What is the Singleton pattern and how is it implemented in Node.js?
Ensures a class has only one instance and provides a global point of access.

class Singleton {
  constructor() {
    if (!Singleton.instance) {
      Singleton.instance = this;
    }
    return Singleton.instance;
  }
}

2. What is the Module Caching mechanism in Node.js?
Modules are cached after the first require, improving performance by not reloading.

3. How does Lazy Loading work in Node.js?
Modules/functions are only loaded when needed to reduce memory footprint.

function loadHeavyModule() {
  const heavy = require('heavy-module');
  heavy.doWork();
}

4. What are the pros and cons of using the EventEmitter pattern?
Pros: decouples components. Cons: harder to trace and debug events.

5. How do you detect a memory leak in a Node.js app?
Use tools like Chrome DevTools, --inspect, heapdump, and memory snapshots.

6. What is backpressure in streams and how do you handle it?
Backpressure occurs when the writable stream cannot process data as fast as readable provides it. Use stream.pause() and stream.resume() or check return value of .write().

7. How do you scale a Node.js application?
Using clustering, horizontal scaling, load balancing, microservices, containerization (Docker), and message queues.

8. What are the best practices for error handling in async/await code?
Always use try/catch blocks and centralized error handlers.

9. What is a throttling mechanism and why is it used?
Throttling limits the number of requests/actions in a given time. Used to prevent abuse and protect backend.

10. What is debouncing and how is it implemented in Node.js?
Delays execution of a function until after a specified time has elapsed since the last time it was invoked.

function debounce(fn, delay) {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
}

11. How can you implement graceful shutdown in Node.js?

process.on('SIGINT', () => {
  server.close(() => {
    console.log('Server closed');
    process.exit(0);
  });
});

12. How can you manage configuration in large Node.js applications?
Use .env files with libraries like dotenv, or configuration libraries like config.

13. What is the role of pm2 in Node.js apps?
Production process manager for Node.js apps. Enables monitoring, clustering, and zero-downtime restarts.

14. How do you measure and monitor performance in Node.js?
Use built-in process module, clinic.js, newrelic, prometheus, and node --inspect.

15. What is the difference between vertical and horizontal scaling?

  • Vertical: Increase resources of one server.

  • Horizontal: Add more servers/nodes.

16. How do you implement request rate limiting?
Use express-rate-limit:

const rateLimit = require('express-rate-limit');
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });
app.use(limiter);

17. What is process clustering and how does it improve performance?
Uses cluster module to run multiple Node.js processes to handle load.

18. How do you use Redis for caching in Node.js?

const redis = require('redis');
const client = redis.createClient();
client.set('key', 'value');
client.get('key', (err, val) => console.log(val));

19. What is the purpose of the os module in performance tuning?
Provides system-level info like memory and CPU load to help in tuning and diagnostics.

20. What is Zero Downtime Deployment and how do you achieve it?
Use process managers like pm2 or blue-green deployments to ensure live app is never interrupted during deploy.

21. How do you profile CPU usage in Node.js?
Use --inspect with Chrome DevTools or clinic doctor to generate CPU profiles.

Section 4: Security & Authentication in Node.js/Express.js (20+ Questions)

1. What is the difference between authentication and authorization?
Authentication verifies who the user is, while authorization checks what the user has access to.

2. How do you implement JWT-based authentication in Express?
Using jsonwebtoken:

const jwt = require('jsonwebtoken');
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });

3. How do you protect Express routes using middleware?

function authMiddleware(req, res, next) {
  const token = req.headers['authorization'];
  if (!token) return res.status(401).send('Access Denied');
  try {
    const verified = jwt.verify(token, process.env.JWT_SECRET);
    req.user = verified;
    next();
  } catch (err) {
    res.status(400).send('Invalid Token');
  }
}

4. What are common security risks in Node.js?

  • XSS

  • CSRF

  • Injection attacks

  • Insecure cookies

  • Exposed sensitive data

5. How do you prevent XSS in Express apps?

  • Use templating engines that auto-escape (e.g., Handlebars)

  • Use helmet

  • Sanitize user input

6. What is Helmet and how does it secure Express apps?
Sets HTTP headers to protect against vulnerabilities:

const helmet = require('helmet');
app.use(helmet());

7. How do you store and validate passwords securely?
Hash passwords using bcrypt before storing:

const bcrypt = require('bcrypt');
const hash = await bcrypt.hash(password, 10);

8. How can you prevent brute-force login attempts?
Use rate-limiting middleware like express-rate-limit.

9. How do you implement session-based authentication in Express?
Use express-session and store session in Redis or DB.

10. What is CSRF and how can you mitigate it?
Cross-site request forgery sends unauthorized commands. Mitigate using csurf middleware.

11. How do HTTPS and SSL certificates work in securing Node.js apps?
Encrypt traffic with SSL; use https.createServer() in production.

12. How can you securely serve static files?
Use express.static, but avoid exposing sensitive directories.

13. What is OAuth and how is it used in Express?
Delegated authorization protocol. Use Passport.js for OAuth strategies.

14. How does Passport.js help in authentication?
Provides strategies for local, OAuth, JWT, etc.

passport.use(new LocalStrategy(...));

15. How do you sanitize user input in Express?
Use libraries like express-validator, sanitize-html, or DOMPurify.

16. How do you secure environment variables in a Node.js app?
Store secrets in .env, load using dotenv, and avoid committing them to source control.

17. What headers should be set for securing Express APIs?

  • Content-Security-Policy

  • X-Frame-Options

  • Strict-Transport-Security

  • X-XSS-Protection

18. How can you detect and log security incidents?
Use monitoring/logging tools (Sentry, DataDog) and audit user actions.

19. What is the best way to revoke a JWT token?
Keep a token blacklist in Redis or use short-lived tokens with refresh tokens.

20. How do you enforce role-based access control in Express?
Define roles and check permissions in middleware before route handlers.

21. What tools help identify security vulnerabilities in Node.js apps?

  • npm audit

  • snyk

  • eslint-plugin-security


Section 5: Testing, Debugging & Deployment in Node.js/Express.js (20+ Questions)

1. How do you write unit tests in Node.js?
Use testing frameworks like Mocha, Jest, or AVA to isolate and test functions.

const assert = require('assert');
describe('sum()', () => {
  it('adds numbers correctly', () => {
    assert.strictEqual(sum(2, 3), 5);
  });
});

2. What is the difference between unit, integration, and end-to-end testing?

  • Unit: individual functions

  • Integration: multiple modules working together

  • E2E: full app flow from UI to backend

3. How do you mock dependencies in tests?
Use tools like sinon, jest.mock(), or proxyquire to replace modules/functions.

4. How do you test Express routes?
Use supertest to simulate requests to your Express app.

const request = require('supertest');
request(app).get('/api/users').expect(200);

5. What is test coverage and how do you measure it?
Use nyc (Istanbul) or Jest’s built-in coverage to report percent of code tested.

6. How do you debug Node.js apps?
Use console.log, Chrome DevTools with --inspect, or Visual Studio Code debugger.

7. What is the --inspect flag in Node.js?
Enables debugging over Chrome DevTools:

node --inspect index.js

8. How can you debug async/await code effectively?
Use breakpoints or wrap in try/catch with verbose logs.

9. What are best practices for writing maintainable test cases?

  • Use descriptive test names

  • Setup and teardown with before and after

  • Keep test logic clean and isolated

10. How do you structure test files in Node.js projects?
Use folders like tests/, and name files with .test.js or .spec.js suffixes.

11. What is CI/CD and how is it used with Node.js apps?
Continuous Integration/Deployment automates testing and deployment using tools like GitHub Actions, Jenkins, GitLab CI.

12. How do you create a Docker image for a Node.js app?

FROM node:18
WORKDIR /app
COPY . .
RUN npm install
CMD ["node", "server.js"]

13. How do you deploy a Node.js app to production?
Options include:

  • PM2 on a VPS

  • Docker + Kubernetes

  • Platforms like Heroku, Vercel, AWS

14. How do you handle environment-based configurations?
Use .env files and process.env.NODE_ENV.

if (process.env.NODE_ENV === 'production') { ... }

15. How do you log errors in production?
Use winston, pino, or services like Sentry for real-time error tracking.

16. What is blue-green deployment?
Deploy app to a new environment, test it, then switch traffic to it with zero downtime.

17. How do you monitor a Node.js app in production?
Use pm2 monit, New Relic, Datadog, AppDynamics, or Prometheus with Grafana.

18. How do you ensure your app recovers from crashes?
Use PM2 with process restart, write exit handlers, and monitor uptime.

19. What are health checks and how do you implement them?
Health check endpoints return 200 if the app is running:

app.get('/health', (req, res) => res.sendStatus(200));

20. What is linting and how do you use it in Node.js?
Use ESLint with Airbnb or Standard configs to enforce consistent code.

21. What are the benefits of containerizing Node.js apps?

  • Environment consistency

  • Easy deployment

  • Scalable architecture

  • Faster onboarding

Section 6: Node.js + Express.js with Databases (MongoDB, SQL) (20+ Questions)

1. What are common databases used with Node.js?

  • NoSQL: MongoDB, CouchDB

  • SQL: PostgreSQL, MySQL, SQLite

2. How do you connect to MongoDB using Mongoose?

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb');

3. What is a Mongoose schema and model?
Defines the structure of MongoDB documents and creates a model to interact with the database.

const UserSchema = new mongoose.Schema({ name: String });
const User = mongoose.model('User', UserSchema);

4. How do you perform CRUD operations with Mongoose?

// Create
const user = await User.create({ name: 'John' });

// Read
const users = await User.find();

// Update
await User.updateOne({ _id: id }, { name: 'Jane' });

// Delete
await User.deleteOne({ _id: id });

5. How do you handle MongoDB errors in Node.js?
Use try/catch and check for validation errors or connection issues.

6. How can you use transactions in MongoDB with Mongoose?
Start a session and use .withTransaction():

const session = await mongoose.startSession();
session.withTransaction(async () => { ... });

7. What is the role of populate() in Mongoose?
It allows joining related collections (like SQL joins).

User.find().populate('profile').exec();

8. How do you define relationships in Mongoose?
Use object references:

const PostSchema = new mongoose.Schema({ author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } });

9. How do you connect to PostgreSQL in Node.js?
Use pg library:

const { Client } = require('pg');
const client = new Client();
await client.connect();

10. How do you perform basic SQL queries in Node.js with pg?

const res = await client.query('SELECT * FROM users');

11. How do you prevent SQL injection in Node.js?
Always use parameterized queries:

client.query('SELECT * FROM users WHERE id = $1', [id]);

12. How do you use an ORM with SQL in Node.js?
Use Sequelize or TypeORM for models, migrations, and easier querying.

13. How do you define a model in Sequelize?

const User = sequelize.define('User', { name: Sequelize.STRING });

14. How do you run migrations in Sequelize?
Use the CLI: npx sequelize-cli db:migrate

15. How do you perform joins in SQL and how is that handled in Sequelize?
Use include:

User.findAll({ include: Post });

16. What are the differences between MongoDB and SQL databases?

  • MongoDB: schema-less, document-based, flexible

  • SQL: schema-driven, relational, strong consistency

17. When should you choose NoSQL over SQL?

  • For flexible, scalable data

  • When relationships are not deeply nested

18. How do you handle pagination in MongoDB and SQL?

  • MongoDB: .skip().limit()

  • SQL: LIMIT and OFFSET

19. How do you index fields in MongoDB and SQL?

  • MongoDB: User.createIndex({ name: 1 });

  • SQL: CREATE INDEX idx_name ON users(name);

20. How do you seed initial data into databases?

  • MongoDB: write a script using Mongoose

  • SQL: use migration/seeder tools (like sequelize-cli) or raw insert scripts

21. How do you use connection pooling in SQL with Node.js?

const pool = new Pool({ max: 20 });
pool.query('SELECT * FROM users');

Section 7: RESTful API Design & Best Practices in Express.js (20+ Questions)

1. What is a RESTful API?
REST (Representational State Transfer) is an architectural style for designing APIs around resources using standard HTTP methods: GET, POST, PUT, DELETE.

2. How do you create a basic RESTful API route in Express.js?

app.get('/users', (req, res) => {
  res.send('User list');
});

3. What are RESTful HTTP methods and what do they represent?

  • GET: Retrieve data

  • POST: Create data

  • PUT: Update entire resource

  • PATCH: Update partial resource

  • DELETE: Remove resource

4. How do you handle route parameters in Express.js?

app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
});

5. How do you validate request bodies in Express?
Use express-validator, Joi, or custom middleware.

6. How do you implement pagination in REST APIs?
Use query params:

GET /users?page=2&limit=10

Then use .skip() and .limit() or SQL OFFSET/LIMIT in DB queries.

7. What is a status code and why is it important in REST?
It tells the client the result of the operation (e.g. 200 OK, 404 Not Found, 400 Bad Request).

8. How do you structure REST API responses?

{
  "success": true,
  "data": [ ... ],
  "message": "Users fetched successfully"
}

9. How do you use middleware in Express.js?
Middleware is a function that has access to req, res, and next. Example:

app.use((req, res, next) => {
  console.log('Request:', req.method);
  next();
});

10. What is the role of next() in middleware?
It passes control to the next middleware/route handler.

11. How do you structure an Express.js project for REST APIs?
Separate concerns into:

  • routes/

  • controllers/

  • services/

  • models/

  • middlewares/

12. How do you handle errors in RESTful APIs?
Use centralized error-handling middleware:

app.use((err, req, res, next) => {
  res.status(err.status || 500).json({ error: err.message });
});

13. What is the difference between PUT and PATCH?

  • PUT replaces the entire resource

  • PATCH updates part of the resource

14. How do you document REST APIs?
Use tools like Swagger/OpenAPI with swagger-jsdoc and swagger-ui-express.

15. What are HATEOAS principles in REST?
Hypermedia as the engine of application state—clients navigate APIs via links.

16. What is the purpose of versioning in REST APIs?
It helps manage breaking changes. Example:

/v1/users
/v2/users

17. How do you protect REST APIs from abuse?

  • Rate limiting

  • Authentication

  • Input validation

  • Logging

18. How do you implement rate limiting in Express.js?
Use express-rate-limit:

const rateLimit = require('express-rate-limit');
app.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 100 }));

19. How do you return paginated metadata in a REST response?

{
  "data": [ ... ],
  "page": 2,
  "limit": 10,
  "total": 125
}

20. How do you standardize API response formats?
Create a response handler utility or middleware that wraps all responses.

21. How do you test RESTful APIs in Express?
Use tools like:

  • Postman

  • Supertest (automated)

  • Jest/Mocha for unit/integration testing


Section 8: Working with File Uploads, Streams, and Buffers in Node.js (20+ Questions)

1. How do you handle file uploads in Express.js?
Use the multer middleware:

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded');
});

2. What is the role of multer?
Multer handles multipart/form-data, stores files temporarily or permanently.

3. How can you store uploaded files in memory with multer?

const storage = multer.memoryStorage();
const upload = multer({ storage });

4. How do you upload multiple files?

upload.array('photos', 3)

5. How do you restrict file types using multer?
Use a custom file filter:

const fileFilter = (req, file, cb) => {
  if (file.mimetype === 'image/png') cb(null, true);
  else cb(new Error('Only PNGs'), false);
};

6. How do you stream a large file to the client?

const fs = require('fs');
app.get('/video', (req, res) => {
  const stream = fs.createReadStream('bigfile.mp4');
  stream.pipe(res);
});

7. What is a stream in Node.js?
A stream is an abstract interface for working with streaming data in chunks.

8. What are the types of streams in Node.js?

  • Readable

  • Writable

  • Duplex

  • Transform

9. How do you create a readable stream?

const fs = require('fs');
const readable = fs.createReadStream('file.txt');

10. How do you write data to a file using streams?

const fs = require('fs');
const writer = fs.createWriteStream('output.txt');
writer.write('Hello');

11. How do you listen for stream events?
Events include data, end, error, finish.

12. What is a buffer in Node.js?
A Buffer is a raw binary data storage structure.

const buf = Buffer.from('Hello');

13. How do you convert buffer to string and vice versa?

buf.toString();
Buffer.from('Hello');

14. How do you handle backpressure in streams?
Check .write() return value and listen for 'drain' event.

15. How do you use pipe() in streams?
Efficient way to connect read/write streams:

readable.pipe(writable);

16. What is the difference between fs.readFile and fs.createReadStream?

  • readFile: loads entire file into memory

  • createReadStream: streams file in chunks

17. How do you compress files using streams?

const zlib = require('zlib');
readable.pipe(zlib.createGzip()).pipe(writable);

18. How do you unzip a stream in Node.js?
Use zlib.createGunzip()

19. How do you stream a remote file in Node.js?
Use http.get() and pipe():

const http = require('http');
http.get(url, (res) => res.pipe(fs.createWriteStream('file.txt')));

20. How do you serve a file download in Express?

res.download('file.pdf');

21. How do you serve static files in Express?

app.use(express.static('public'));

Section 9: Building Realtime Applications with WebSockets in Node.js (Expanded)

1. What is a WebSocket?
A WebSocket is a persistent connection between client and server that allows real-time two-way communication.

2. How is WebSocket different from HTTP?

  • HTTP: stateless, request-response

  • WebSocket: persistent, full-duplex communication

3. Which package is commonly used for WebSocket in Node.js?
ws or socket.io

4. How do you set up a WebSocket server using ws?

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
  ws.on('message', message => console.log('received:', message));
  ws.send('Hello client');
});

5. How do you integrate WebSocket with an Express server?
Use http.createServer():

const http = require('http');
const server = http.createServer(app);
const WebSocket = require('ws');
const wss = new WebSocket.Server({ server });

6. How do you broadcast messages to all clients in ws?

wss.clients.forEach(client => {
  if (client.readyState === WebSocket.OPEN) {
    client.send('broadcast');
  }
});

7. What is Socket.IO and how is it different from ws?
Socket.IO is a higher-level abstraction over WebSockets that provides fallbacks (polling, etc.), built-in reconnection, and support for rooms and namespaces.

8. How do you set up a Socket.IO server?

const { Server } = require('socket.io');
const io = new Server(server);
io.on('connection', socket => {
  socket.emit('welcome', 'Hi user!');
});

9. How do you handle custom events in Socket.IO?

socket.on('chat message', (msg) => {
  io.emit('chat message', msg);
});

10. How do you create chat rooms in Socket.IO?

socket.join('room1');
io.to('room1').emit('msg', 'Hello room');

11. How do you authenticate WebSocket connections?
With ws, inspect headers/tokens during the connection. With Socket.IO:

io.use((socket, next) => {
  const token = socket.handshake.auth.token;
  if (isValidToken(token)) return next();
  next(new Error('Authentication error'));
});

12. How do you send binary data over WebSocket?
Send Buffer objects:

ws.send(Buffer.from([1, 2, 3]));

13. What are common WebSocket events?

  • open: connection established

  • message: message received

  • error: error occurred

  • close: connection closed

14. How do you detect disconnection in WebSocket?
Listen for the close event:

ws.on('close', () => console.log('Client disconnected'));

15. How do you reconnect automatically with Socket.IO?
The client handles this by default. You can configure retry behavior:

const socket = io('http://localhost:3000', {
  reconnectionAttempts: 5,
  reconnectionDelay: 1000
});

16. How do you scale Socket.IO with multiple instances?
Use socket.io-redis adapter:

const { createAdapter } = require('@socket.io/redis-adapter');
const pubClient = createClient();
const subClient = pubClient.duplicate();
io.adapter(createAdapter(pubClient, subClient));

17. What is the role of ping/pong frames in WebSocket?
Used to detect dead connections and maintain keep-alive state.

18. How do you handle backpressure in WebSocket?
Avoid sending data too fast. Monitor socket.bufferedAmount or ws.bufferedAmount and pause if it exceeds thresholds.

19. Can you use WebSocket over HTTPS?
Yes. Use wss:// with a secure HTTPS server:

const server = https.createServer({ key, cert }, app);
const wss = new WebSocket.Server({ server });

20. How do you integrate WebSocket with frontend clients?
WebSocket:

const socket = new WebSocket('ws://localhost:8080');
socket.onmessage = e => console.log(e.data);

Socket.IO:

const socket = io('http://localhost:3000');
socket.on('welcome', msg => console.log(msg));
Scroll to Top