Nodejs
179 bites tagged Nodejs — interview questions with model answers, and 60-second explainers.
Auditing and fixing vulnerable npm dependencies
Run npm audit (or yarn audit) to list advisories, npm audit fix to patch within semver, bump majors deliberately, and lock versions; wire audits into CI. Practical dependency hygiene.
Input validation versus output encoding
Validation checks input fits expected rules on entry; encoding makes data safe for a specific output context on exit. You need both; encoding is the real anti-XSS control. Knowing these are complementary, not interchangeable.
Preventing SQL injection with parameterized queries
The flaw is SQL injection; prevent it with parameterized queries/prepared statements (pg $1, mysql2 ?), never string concatenation, so input is data not code. Knowing SQL injection and parameterization.
Explaining and preventing CSRF in Express
CSRF abuses a victim's ambient cookies to forge state-changing requests; the server issues an unpredictable token tied to the session, embeds it in forms, and validates it… Understanding CSRF and the synchronizer-token pattern.
Preventing XSS when rendering user content in templates
The risk is XSS; default to escaped interpolation (EJS <%= %>, Pug #{}) so HTML is encoded, and avoid raw output (<%- %>) for untrusted data. Knowing XSS and contextual output encoding.
Purpose of Helmet middleware in Express
Helmet sets safe response headers like X-Content-Type-Options, HSTS, and CSP, mitigating MIME-sniffing, clickjacking, and protocol downgrade. Awareness of HTTP security headers and defense in depth.
Testing an async workflow that spans DB and message queue
Assert the DB row, then verify the queue message via a test consumer or spy, polling with a timeout rather than fixed sleeps. Verifying side effects that finish after the HTTP response.
Testing code that calls a third-party API
Intercept at the HTTP boundary (nock) or run a local mock server; cover success, errors, timeouts, and assert request shape. How you fake external HTTP without real network calls.
Managing clean test state across API integration tests
Compare seed-and-truncate, per-test transaction rollback, and in-memory or containerized databases, weighing fidelity, speed, and isolation. How you keep integration tests isolated and fast.
Testing async Promise-returning code in Jest
Return or await the promise; use await expect(...).resolves/rejects, or await the value directly. Whether you make async assertions actually run before the test ends.
Mocking the database layer in Jest unit tests
A live DB makes tests slow, flaky, and order-dependent; use jest.mock on the model so methods return controlled fakes. Whether you isolate units from slow, stateful dependencies.
Integration testing a POST endpoint with Supertest
Pass the Express app to supertest, send a POST with a body, then assert status 201, the response shape, and the persisted side effect; also test validation failures. HTTP-level integration testing.
Writing a basic Jest unit test
Import the function, group cases with describe, define each case with it or test, assert with expect and a matcher like toBe, covering normal and edge inputs. Jest fundamentals.
Handling uncaughtException and unhandledRejection
Listen on process for uncaughtException and unhandledRejection, log the error, stop accepting new work, drain in-flight requests, then exit non-zero for a supervisor to restart. process-level last-resort error handling.
Operational versus programmer errors in Node.js
Operational errors are expected runtime conditions you handle and respond to; programmer errors are bugs that may corrupt state, so you log and gracefully restart. error classification and recovery policy.
Custom Error classes and centralized handling
Custom Error subclasses carry a statusCode and flag, the central handler inspects instanceof or statusCode to set the HTTP code and JSON shape, defaulting unknown errors to 500. structured error design.
Propagating async errors to Express error handlers
Express does not auto-catch rejected promises, so catch and call next(err), or wrap handlers in an asyncHandler that forwards rejections; Express 5 awaits handlers automatically. async error forwarding.
Basic presence validation on a POST login route
Ensure the JSON body parser runs, destructure email and password from req.body, return 400 early if either is missing, then proceed. minimal input validation.
Mongoose pre('save') hooks for password hashing
Pre('save') runs before persistence; use it to hash the password, guarding with isModified, calling next() or returning. lifecycle hooks on documents.
Database migrations with the Sequelize CLI
Migrations are version-controlled scripts with up/down so teams apply identical schema changes; use sequelize-cli to generate, edit with addColumn, then db:migrate. versioned, repeatable schema changes.
Mongoose populate() for referenced documents
Populate() replaces stored ObjectIds with the referenced documents, needs a ref in the schema, called via .populate('author'). resolving references across collections.
Define a Mongoose schema and model
New mongoose.Schema with field options (type, required, default), then mongoose.model('Product', schema) to get a model. schema syntax and the schema-to-model step.
API versioning: URL vs header strategies
Version via URL path (/v1/), a custom or Accept header, or a query param; URL is visible and cache-friendly, headers keep URLs clean but are less discoverable. managing breaking changes.
Centralized error handling in an Express API
A final four-arg error middleware, an asyncHandler wrapper to funnel promise rejections via next, a custom error class with statusCode, returning uniform JSON. designing one error path.
Get Nodejs bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.