HackerRank Express.js Skills Certification — Questions and Answers
Question 1: Which HTTP method does app.delete() handle in Express?
- REMOVE
- DESTROY
- ERASE
- DELETE (Correct answer)
Correct answer: DELETE
app.delete() registers a route handler for the HTTP DELETE method.
Question 2: How do you pass a custom error to the Express error handler from a route?
- throw new Error('message')
- app.error(new Error('message'))
- next(new Error('message')) (Correct answer)
- res.error(new Error('message'))
Correct answer: next(new Error('message'))
Calling next() with an Error object routes the error to the next error-handling middleware.
Question 3: What does idempotency mean in the context of REST APIs?
- Requests are automatically retried on failure
- Only one client can access an endpoint at a time
- Making the same request multiple times produces the same result as making it once (Correct answer)
- Requests are processed in order
Correct answer: Making the same request multiple times produces the same result as making it once
Idempotent methods (GET, PUT, DELETE) return the same result regardless of how many times they're called with the same input.
Question 4: What is the default HTTP status code Express sends if an error reaches the error handler without res.status() being set?
- 404
- 400
- 500 (Correct answer)
- 503
Correct answer: 500
Express uses a 500 Internal Server Error status by default when an error reaches the error handler without an explicit status code.
Question 5: What does res.sendFile() do in Express?
- Uploads a file to the server
- Caches a file in memory
- Streams a file to another server
- Sends a file as the HTTP response with appropriate Content-Type (Correct answer)
Correct answer: Sends a file as the HTTP response with appropriate Content-Type
res.sendFile() transfers a file at the given path as the response, automatically setting the Content-Type header.
Question 6: What HTTP header is conventionally used to send a JWT in an API request?
- Authorization: Bearer <token> (Correct answer)
- X-Auth-Token: <token>
- Auth: JWT <token>
- Token: <token>
Correct answer: Authorization: Bearer <token>
The Bearer token scheme in the Authorization header is the standard way to transmit JWTs with API requests.
Question 7: What does req.fresh return in Express?
- True if the connection is new
- True if the request has no body
- True if the response is considered 'not modified' based on cache headers (Correct answer)
- True if the request was just received
Correct answer: True if the response is considered 'not modified' based on cache headers
req.fresh checks Last-Modified and ETag headers to determine if the cached response is still valid (HTTP 304 logic).
Question 8: What happens if a middleware function does not call next() or send a response?
- Express automatically sends a 200 OK
- The request hangs and the client never receives a response (Correct answer)
- Express throws an error
- The next middleware runs anyway
Correct answer: The request hangs and the client never receives a response
Without calling next() or sending a response, the request-response cycle stalls and the client times out.
Question 9: How many parameters must an Express error-handling middleware function declare?
- 4 (err, req, res, next) (Correct answer)
- 5 (err, req, res, next, app)
- 3 (err, req, res)
- 2 (err, next)
Correct answer: 4 (err, req, res, next)
Express identifies error-handling middleware by its four-parameter signature: err, req, res, and next.
Question 10: What is the name of the procedure for utilizing values?
- includes
- inheritance
- interpolation (Correct answer)
- filters
Correct answer: interpolation
Explanation: <br> Interpolation is a method of utilizing values.
Question 11: What is SQL injection and how do you prevent it in an Express app using a database?
- Malicious SQL in inputs; prevent by using parameterized queries or an ORM (Correct answer)
- A type of CSRF attack
- A server misconfiguration issue
- Injecting SQL via HTTP headers only
Correct answer: Malicious SQL in inputs; prevent by using parameterized queries or an ORM
SQL injection occurs when untrusted input is concatenated into SQL strings; parameterized queries or ORMs prevent it by separating data from code.
Question 12: What does the secure: true option do when setting cookies in Express?
- Encrypts the cookie value
- Ensures the cookie is only sent over HTTPS connections (Correct answer)
- Prevents the cookie from being accessed by scripts
- Sets a short expiration time
Correct answer: Ensures the cookie is only sent over HTTPS connections
The secure flag instructs browsers to only send the cookie over encrypted HTTPS connections.
Question 13: What is the purpose of bcrypt when handling passwords in an Express application?
- Hashing passwords with a salt to securely store them (Correct answer)
- Encrypting passwords for transmission
- Validating password format
- Generating JWT secrets
Correct answer: Hashing passwords with a salt to securely store them
bcrypt applies a cost factor and salt to create a one-way hash, making password storage secure against rainbow table attacks.
Question 14: How do you validate request body data in an Express REST API?
- Use built-in Express validation
- Use validation middleware like express-validator or joi before the route handler (Correct answer)
- Validate inside the database layer only
- Rely on TypeScript types at runtime
Correct answer: Use validation middleware like express-validator or joi before the route handler
Middleware libraries like express-validator or joi validate and sanitize incoming data before it reaches business logic.
Question 15: How can you define multiple callback functions for a single route in Express?
- Use app.multi()
- Pass them as multiple arguments or an array to app.get() (Correct answer)
- Nest route definitions
- Use app.chain()
Correct answer: Pass them as multiple arguments or an array to app.get()
Express allows passing multiple middleware functions as separate arguments or in an array to route methods.
Question 16: What is the primary purpose of JSON Web Tokens (JWT) in an Express application?
- Storing session data server-side
- Encrypting database connections
- Compressing JSON payloads
- Stateless authentication by encoding user identity in a signed token (Correct answer)
Correct answer: Stateless authentication by encoding user identity in a signed token
JWTs carry signed claims about a user, enabling stateless authentication without server-side session storage.
Question 17: Which property of the request object contains the parsed body of a POST request with JSON content?
- req.content
- req.payload
- req.body (Correct answer)
- req.data
Correct answer: req.body
After applying express.json() middleware, the parsed JSON body is available on req.body.
Question 18: In terms of route parameters, where are the captured values populated?
- All of the above
- app.locals
- req.params (Correct answer)
- req.data
Correct answer: req.params
Explanation: <br> URL segments, also known as route parameters, are used to record the data supplied at their place in the URL. The req is filled with the captured values. The name of the route parameter supplied in the path is the key of the params object.
Question 19: How do you mount a router module at the path '/api' in Express?
- app.route('/api', router)
- app.mount('/api', router)
- app.use('/api', router) (Correct answer)
- app.attach('/api', router)
Correct answer: app.use('/api', router)
app.use() mounts middleware or a router at a specified path prefix.
Question 20: What is the purpose of setting httpOnly: true on session cookies in Express?
- Expires the cookie after one request
- Forces HTTPS for the cookie
- Limits the cookie to the same origin
- Prevents client-side JavaScript from accessing the cookie (Correct answer)
Correct answer: Prevents client-side JavaScript from accessing the cookie
The httpOnly flag prevents XSS attacks from stealing the session cookie via document.cookie in the browser.
Question 21: Which popular third-party middleware is used for logging HTTP requests in Express?
- morgan (Correct answer)
- bunyan
- winston
- log4js
Correct answer: morgan
morgan is the most widely used Express HTTP request logger middleware.
Question 22: What benefit does setting a default 'view engine' provide in Express?
- Removes the need to specify file extensions in res.render() calls (Correct answer)
- Generates templates automatically from JSON route definitions
- Enables hot-reloading of template files during development
- Automatically installs the template engine npm package
Correct answer: Removes the need to specify file extensions in res.render() calls
With a default view engine set, res.render('index') resolves to 'index.ejs' (or the configured extension) without requiring the caller to include the extension.
Question 23: What HTTP method should be used for partial updates to a resource in REST?
- PATCH (Correct answer)
- UPDATE
- POST
- PUT
Correct answer: PATCH
PATCH is intended for partial modifications, while PUT replaces the entire resource representation.
Question 24: What is the purpose of router.param() in Express?
- Validates query parameters
- Sets default parameter values
- Defines optional route segments
- Adds a callback triggered when a specific route parameter is present (Correct answer)
Correct answer: Adds a callback triggered when a specific route parameter is present
router.param() registers a callback that runs whenever a specific named parameter appears in a route.
Question 25: We'll need a node client API to use Mongo with Express.js.
- True (Correct answer)
- Cannot say
- False
- Can be true or false
Correct answer: True
Explanation: <br> A client API for the node is required to use Mongo with Express.
Question 26: How do you set a response header in Express?
- res.addHeader('Header-Name', 'value')
- res.headers.push()
- res.header['Header-Name'] = 'value'
- res.set('Header-Name', 'value') or res.setHeader() (Correct answer)
Correct answer: res.set('Header-Name', 'value') or res.setHeader()
res.set() (or res.header()) sets response headers, supporting both single and multiple header values.
Question 27: Which Express middleware pattern handles 404 Not Found errors for unmatched routes?
- Set app.notFound = handler
- Add a catch-all app.use() at the end that calls next(createError(404)) (Correct answer)
- Use app.error(404, handler)
- Use app.on('404', handler)
Correct answer: Add a catch-all app.use() at the end that calls next(createError(404))
A catch-all middleware placed after all routes and before the error handler catches unmatched requests and generates a 404 error.
Question 28: What built-in Express middleware serves a directory listing or static files from a path?
- express.files()
- express.static() (Correct answer)
- express.directory()
- express.serve()
Correct answer: express.static()
express.static() serves static files from the specified root directory and is the only built-in static file server in Express.
Question 29: What is the SameSite cookie attribute and why is it important in Express apps?
- Restricts cookies to a single subdomain
- Limits cookie size
- Controls whether cookies are sent with cross-site requests, helping prevent CSRF (Correct answer)
- Forces same-origin API calls only
Correct answer: Controls whether cookies are sent with cross-site requests, helping prevent CSRF
Setting SameSite=Strict or Lax prevents browsers from sending session cookies with cross-site requests, blocking most CSRF attacks.
Question 30: In EJS, which tag executes JavaScript code without rendering any output to the page?
- <%= %>
- <%- %>
- <%_ %>
- <% %> (Correct answer)
Correct answer: <% %>
<% %> is the scriptlet tag used for control flow (if/for/etc.) and executes code without writing output.
HackerRank Express.js Skills Certification
Assesses proficiency in building web applications and RESTful APIs with Express.js, covering routing, middleware, error handling, security, and authentication patterns for Node.js backend development.
Exam Rules
- You can skip questions and return to them later
- Flag questions for review before submitting
- No feedback shown until you submit the entire exam
- Unanswered questions count as wrong — answer everything
- 10 pretest questions are mixed in and don't affect your score
- Timer auto-submits when time runs out
- Your progress is auto-saved every 30 seconds