Skip to content

Full Stack with Node.js Online Assessment Questions & Answers

40 questions for the online assessment stage — 18 easy, 22 medium.

About the online assessment round

Most companies start with an online test: aptitude and reasoning, a few MCQs on core Full Stack with Node.js concepts, and one or two short hands-on tasks. It filters a large number of applicants, so speed and accuracy both count.

Tips for the online assessment round

  • Practise under a timer: about one minute per MCQ and 15-20 minutes per hands-on task.
  • Read every option before answering; tests often include two nearly correct choices.
  • Use a stable internet connection, keep your camera on and avoid switching tabs in proctored tests.
  • Attempt the questions you are sure about first, then return to the harder ones.
Solved — online assessmentStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Write signup and login handlers using bcrypt.

Save to ▾
Show answer
const bcrypt = require('bcrypt'); async function signup(req, res) { const hash = await bcrypt.hash(req.body.password, 12); const user = await User.create({ email: req.body.email, password: hash }); res.status(201).json({ id: user.id }); } async function login(req, res) { const user = await User.findOne({ email: req.body.email }).select('+password'); const ok = user && await bcrypt.compare(req.body.password, user.password); if (!ok) return res.status(401).json({ error: 'Invalid credentials' }); res.json({ token: signAccessToken(user) }); }
02

How do you handle file uploads in Express?

Save to ▾
Show answer
Use multer for multipart/form-data. Configure limits for file size and count, filter allowed MIME types and extensions, and store files with generated names, not user-supplied names. For production, stream uploads directly to object storage such as S3 using presigned URLs so files do not pass through or fill the server disk. Scan files and never execute uploaded content.
03

Implement cursor-based pagination for a products endpoint.

Save to ▾
Show answer
router.get('/products', async (req, res) => { const limit = Math.min(Number(req.query.limit) || 20, 100); const cursor = req.query.cursor; const filter = cursor ? { _id: { $lt: cursor } } : {}; const items = await Product.find(filter) .sort({ _id: -1 }) .limit(limit + 1); const hasMore = items.length > limit; if (hasMore) items.pop(); res.json({ data: items, nextCursor: hasMore ? items[items.length - 1]._id : null }); });
04

What is the difference between REST and GraphQL?

Save to ▾
Show answer
REST exposes multiple endpoints with fixed response shapes, uses HTTP caching easily and is simple to reason about. GraphQL exposes one endpoint where clients query exactly the fields they need, reducing over-fetching and multiple round trips, which helps mobile apps. GraphQL adds complexity: N+1 query risks needing DataLoader, harder caching, query cost limits and schema governance.
05

What is the output order of this code: console.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); console.log('D');

Save to ▾
Show answer
The output is A, D, C, B. Synchronous code runs first, printing A and D. Then the microtask queue is drained before the event loop moves to timers, so the promise callback prints C. Finally the timers phase runs the setTimeout callback and prints B. Microtasks always run before the next macrotask such as timers or I/O callbacks.
06

How does the this keyword behave in arrow functions compared to regular functions?

Save to ▾
Show answer
A regular function's this depends on how it is called: the object before the dot, undefined in strict mode for plain calls, or whatever bind, call or apply set. Arrow functions do not have their own this; they capture it lexically from the surrounding scope. That makes arrows ideal for callbacks inside class methods, but unsuitable as object methods that need this.
07

Explain ACID properties of a database transaction.

Save to ▾
Show answer
Atomicity means all operations in a transaction succeed or none do. Consistency means the database moves from one valid state to another, respecting constraints. Isolation means concurrent transactions do not see each other's partial work, controlled by isolation levels. Durability means committed data survives crashes. Money transfers rely on ACID so a debit never happens without the matching credit.
08

Write a Jest unit test for a function that calculates order total with GST.

Save to ▾
Show answer
// pricing.js const total = (items, gst = 0.18) => Math.round(items.reduce((s, i) => s + i.price * i.qty, 0) * (1 + gst) * 100) / 100; module.exports = { total }; // pricing.test.js const { total } = require('./pricing'); describe('total', () => { it('adds 18% GST by default', () => { expect(total([{ price: 100, qty: 2 }])).toBe(236); }); it('returns 0 for an empty cart', () => { expect(total([])).toBe(0); }); });
09

Write a basic GitHub Actions workflow that tests and builds a Node.js app.

Save to ▾
Show answer
name: ci on: [push, pull_request] jobs: test: runs-on: ubuntu-latest services: mongo: image: mongo:7 ports: ['27017:27017'] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: npm - run: npm ci - run: npm run lint - run: npm test -- --coverage env: MONGO_URL: mongodb://localhost:27017/test
10

What is an index and how does it improve query performance?

Save to ▾
Show answer
An index is a data structure, usually a B-tree, that lets the database find rows without scanning the whole table or collection. Indexes speed up reads on filtered, sorted and joined fields but slow down writes and use storage. Create them based on real query patterns, check usage with EXPLAIN or explain('executionStats'), and remove unused ones.
11

What is Express.js and why is it widely used?

Save to ▾
Show answer
Express is a minimal, unopinionated web framework for Node.js that adds routing, middleware and helpers for requests and responses on top of the http module. It is widely used because it is simple, flexible and has a large ecosystem of middleware for logging, auth, validation and security. Many teams also use it as the base for frameworks like NestJS.
12

How do you implement rate limiting on a login endpoint?

Save to ▾
Show answer
const rateLimit = require('express-rate-limit'); const { RedisStore } = require('rate-limit-redis'); const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 5, standardHeaders: 'draft-7', legacyHeaders: false, keyGenerator: (req) => `${req.ip}:${req.body.email}`, store: new RedisStore({ sendCommand: (...a) => redis.sendCommand(a) }) }); app.post('/auth/login', loginLimiter, login); // Add account lockout or CAPTCHA after repeated failures.
13

What is the N+1 query problem and how do you fix it?

Save to ▾
Show answer
N+1 happens when you run one query to fetch a list and then one extra query per item, for example loading 100 posts and then each author separately, causing 101 queries. Fix it with joins or eager loading in SQL ORMs like include in Prisma or Sequelize, populate or $lookup in MongoDB, batching with an IN query, or DataLoader in GraphQL.
14

What is SQL injection and how do you prevent it in Node.js?

Save to ▾
Show answer
SQL injection happens when user input is concatenated into a query, letting attackers change it, for example ' OR 1=1 --. Prevent it with parameterised queries, such as pool.query('SELECT * FROM users WHERE email = $1', [email]) in pg, or an ORM like Prisma or Sequelize that parameterises automatically. Also validate input and give the database user minimum privileges.
15

What is the difference between SQL and NoSQL databases?

Save to ▾
Show answer
SQL databases such as PostgreSQL and MySQL store data in tables with fixed schemas, support joins and strong ACID transactions, and suit relational data like orders and payments. NoSQL databases such as MongoDB, Redis or Cassandra use documents, key-value or wide-column models with flexible schemas and easier horizontal scaling. The choice depends on data relationships, consistency needs and query patterns.
16

How do you enable compression and why should you be careful with it?

Save to ▾
Show answer
Use the compression middleware or, better, let Nginx or the CDN compress responses with gzip or Brotli, which reduces JSON payload size by 70 percent or more. Be careful: compressing in Node uses CPU on the event loop, small responses gain little, and already compressed files like images should be skipped. Never compress responses mixing secrets with user input over HTTPS because of BREACH-style attacks.
17

How do access tokens and refresh tokens work together?

Save to ▾
Show answer
The access token is short-lived, around 5 to 15 minutes, and sent with each API request. The refresh token is long-lived, stored securely in an HttpOnly cookie, and used only at a refresh endpoint to get a new access token. Rotate refresh tokens on every use and store their hashes server-side, so a stolen or reused token can be detected and the session revoked.
18

Compare session-based authentication with JWT-based authentication.

Save to ▾
Show answer
Sessions store state on the server, often in Redis, and the client holds only a session ID cookie; logout and revocation are easy. JWTs are stateless, so any service can verify them without a lookup, which suits microservices and mobile apps, but revoking a token before expiry needs a denylist or short lifetimes. Many systems combine short-lived JWT access tokens with server-stored refresh tokens.
19

Write a simple Docker Compose file to run a Node API with MongoDB and Redis locally.

Save to ▾
Show answer
services: api: build: . ports: ['3000:3000'] environment: MONGO_URL: mongodb://mongo:27017/app REDIS_URL: redis://redis:6379 depends_on: [mongo, redis] mongo: image: mongo:7 volumes: ['mongo-data:/data/db'] redis: image: redis:7-alpine volumes: mongo-data:
20

What is a closure and how is it used in Node.js code?

Save to ▾
Show answer
A closure is a function that remembers variables from the scope where it was created, even after that outer function has returned. In Node it is used for middleware factories like rateLimit({ max: 100 }), private counters, memoisation and module-level state. A risk is memory leaks when closures hold large objects longer than needed, for example inside long-lived event listeners.
21

Write JWT authentication middleware for Express.

Save to ▾
Show answer
const jwt = require('jsonwebtoken'); function authenticate(req, res, next) { const header = req.get('Authorization') || ''; const token = header.startsWith('Bearer ') ? header.slice(7) : null; if (!token) return res.status(401).json({ error: 'Missing token' }); try { req.user = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }); next(); } catch { res.status(401).json({ error: 'Invalid or expired token' }); } }
22

What is a Promise and what are its states?

Save to ▾
Show answer
A Promise is an object representing the eventual result of an asynchronous operation. It has three states: pending, fulfilled with a value, or rejected with a reason. Once settled it never changes. You consume it with then, catch and finally, or with await. Promises chain, so returning a value or promise from then passes it to the next step.
23

How do you run async tasks in parallel versus in sequence?

Save to ▾
Show answer
// Sequential: each waits for the previous one for (const id of ids) { const user = await getUser(id); results.push(user); } // Parallel: start all, then wait together const users = await Promise.all(ids.map((id) => getUser(id))); // Use sequential only when steps depend on each other // or when you must limit load on a downstream service.
24

Write a simple custom EventEmitter usage for an order service.

Save to ▾
Show answer
const EventEmitter = require('events'); class OrderService extends EventEmitter { place(order) { // save order... this.emit('placed', order); } } const svc = new OrderService(); svc.on('placed', (o) => console.log('Send email for', o.id)); svc.once('placed', () => console.log('First order today')); svc.on('error', (err) => console.error(err)); svc.place({ id: 101 });
25

How can you cancel an in-flight HTTP request in Node.js?

Save to ▾
Show answer
Use AbortController. Create a controller, pass controller.signal to fetch or to libraries that support it such as axios, and call controller.abort() when the request is no longer needed, for example when the client disconnects. AbortSignal.timeout(ms) gives a ready-made timeout signal. Aborting rejects the promise with an AbortError, which you should handle separately from real failures.
26

What is Mongoose and why use it with MongoDB?

Save to ▾
Show answer
Mongoose is an ODM for MongoDB in Node.js. It adds schemas with types, validation, defaults, middleware hooks such as pre save, virtuals, population of references and a convenient query API. This brings structure to schemaless MongoDB collections and reduces bugs. For very high-performance or simple cases, some teams use the native MongoDB driver directly to avoid the overhead.
27

How do you mock a database or external service in Jest?

Save to ▾
Show answer
// order.service.test.js jest.mock('../repositories/orderRepo'); const repo = require('../repositories/orderRepo'); const { cancelOrder } = require('../services/order.service'); test('cannot cancel a shipped order', async () => { repo.findById.mockResolvedValue({ id: 1, status: 'shipped' }); await expect(cancelOrder(1)).rejects.toThrow('Cannot cancel'); expect(repo.update).not.toHaveBeenCalled(); }); // For HTTP calls, nock or msw can intercept requests.
28

How does HTTP caching with ETag and Cache-Control work for APIs?

Save to ▾
Show answer
Cache-Control tells clients and CDNs how long a response is fresh, for example public, max-age=300, or private, no-store for user data. An ETag is a hash of the response; the client sends it back in If-None-Match, and if nothing changed the server returns 304 Not Modified with no body. Express generates weak ETags automatically for res.send responses.
29

What are streams in Node.js and what types exist?

Save to ▾
Show answer
Streams process data in chunks instead of loading everything into memory. There are four types: Readable (fs.createReadStream, HTTP request), Writable (fs.createWriteStream, HTTP response), Duplex (TCP socket, both read and write) and Transform (zlib gzip, modifies data as it passes). Streams keep memory flat when serving large files, uploading media or processing big CSV logs.
30

How do you enable CORS in an Express app and why is it needed?

Save to ▾
Show answer
Browsers block cross-origin requests unless the server sends CORS headers. Use the cors package: app.use(cors({ origin: ['https://app.example.com'], credentials: true })). Avoid origin '*' with credentials, and restrict methods and headers you allow. CORS is a browser protection, not a security layer for your API, so you still need authentication and authorisation.
31

What is a REST API and what are its key constraints?

Save to ▾
Show answer
REST is an architectural style where resources are identified by URLs and manipulated through standard HTTP methods. Key constraints: client-server separation, statelessness so each request carries all needed information, cacheable responses, uniform interface, layered system and optionally code on demand. In practice it means resource-based URLs, correct methods and status codes, and JSON representations.
32

Write a simple request logging middleware that records response time.

Save to ▾
Show answer
function requestLogger(req, res, next) { const start = process.hrtime.bigint(); res.on('finish', () => { const ms = Number(process.hrtime.bigint() - start) / 1e6; console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${ms.toFixed(1)}ms`); }); next(); } app.use(requestLogger); // In production use pino-http or morgan with structured logs.
33

How would you test code that depends on the current time, like an expiring coupon?

Save to ▾
Show answer
Inject a clock function instead of calling Date.now directly, or use Jest fake timers: jest.useFakeTimers().setSystemTime(new Date('2026-01-01')). Then test before, exactly at and after expiry. Store dates in UTC and convert for display in IST, which avoids bugs near midnight. Reset timers after each test with jest.useRealTimers to avoid leaking into other tests.
34

Explain the main HTTP methods and which are idempotent.

Save to ▾
Show answer
GET reads a resource, POST creates or triggers an action, PUT replaces a resource fully, PATCH updates part of it and DELETE removes it. GET, PUT, DELETE, HEAD and OPTIONS are idempotent, meaning repeating the request has the same effect as doing it once. POST and usually PATCH are not, which is why payment APIs use idempotency keys for POST.
35

How does error-handling middleware work in Express?

Save to ▾
Show answer
Error-handling middleware has four parameters (err, req, res, next) and must be registered after all routes. When any middleware calls next(err) or throws in a synchronous handler, Express skips normal middleware and jumps to the error handler. In Express 4, async errors must be passed to next manually or with a wrapper; Express 5 forwards rejected promises automatically.
36

How do you manage database schema migrations in a Node.js project?

Save to ▾
Show answer
Use a migration tool such as Prisma Migrate, Knex, Sequelize CLI or TypeORM migrations, and commit migration files to Git. Each migration has up and ideally down steps and runs in CI and before deployment. For zero downtime, use expand and contract: add new columns first, deploy code that writes both, backfill, switch reads, then drop old columns in a later release.
37

What is the difference between process.nextTick and setImmediate?

Save to ▾
Show answer
process.nextTick queues a callback to run immediately after the current operation, before the event loop continues to any phase, even before promise microtasks. setImmediate queues a callback for the check phase of the next loop iteration. Overusing nextTick recursively can starve I/O because the loop never moves on, so setImmediate is safer for deferring heavy work.
38

What are XSS and CSRF and how do you protect a Node.js app from them?

Save to ▾
Show answer
XSS injects malicious script into pages other users view; prevent it by escaping output, using templating or React auto-escaping, sanitising rich HTML with DOMPurify and setting a strong Content-Security-Policy. CSRF tricks a logged-in browser into sending unwanted requests; prevent it with SameSite cookies, CSRF tokens for cookie-based auth and checking Origin headers on state-changing requests.
39

How do you manage secrets such as database passwords and API keys in a Node.js app?

Save to ▾
Show answer
Never commit secrets to Git. Load them from environment variables, using a .env file only for local development and keeping it in .gitignore. In production, use a secrets manager such as AWS Secrets Manager, Azure Key Vault, HashiCorp Vault or Kubernetes secrets with encryption. Rotate keys regularly, scan repos with tools like gitleaks and validate required variables at startup.
40

Explain semantic versioning and the meaning of ^ and ~ in package.json.

Save to ▾
Show answer
Semantic versioning uses MAJOR.MINOR.PATCH: major for breaking changes, minor for new backward-compatible features, patch for bug fixes. A caret like ^4.18.2 allows any 4.x.x at or above 4.18.2. A tilde like ~4.18.2 allows only patch updates, 4.18.x. An exact version pins it. The lock file still decides what is actually installed.

Frequently asked questions

What happens in the Full Stack with Node.js online assessment round?

Most companies start with an online test: aptitude and reasoning, a few MCQs on core Full Stack with Node.js concepts, and one or two short hands-on tasks. It filters a large number of applicants, so speed and accuracy both count.

How do I clear the online assessment round?

Practise under a timer: about one minute per MCQ and 15-20 minutes per hands-on task. Read every option before answering; tests often include two nearly correct choices. Use a stable internet connection, keep your camera on and avoid switching tabs in proctored tests.

Which round comes next?

A typical order is online assessment, telephonic screening, one or two technical rounds, a managerial round and HR. Use the other round pages to practise each stage.