HackerRank Express.js Skills Certification — Questions and Answers
Question 1: Which property of the request object contains the parsed body of a POST request with JSON content?
- req.payload
- req.body (Correct answer)
- req.content
- req.data
Correct answer: req.body
After applying express.json() middleware, the parsed JSON body is available on req.body.
Question 2: What does the express-async-errors package do?
- Provides async route validation
- Patches Express to automatically catch rejected promises in async handlers (Correct answer)
- Enables async middleware registration
- Adds async logging
Correct answer: Patches Express to automatically catch rejected promises in async handlers
express-async-errors monkey-patches Express router methods to automatically catch rejected promises and forward them via next(err).
Question 3: What does the helmet package help protect against in Express?
- Brute-force login attempts
- SQL injection
- XSS, clickjacking, and other attacks by setting security HTTP headers (Correct answer)
- CSRF only
Correct answer: XSS, clickjacking, and other attacks by setting security HTTP headers
helmet sets headers like Content-Security-Policy, X-Frame-Options, and Strict-Transport-Security to mitigate common web attacks.
Question 4: Which middleware is commonly used to prevent Cross-Site Request Forgery (CSRF) in Express apps with sessions?
- csurf (or modern alternatives like csrf-csrf) (Correct answer)
- helmet
- cors
- express-validator
Correct answer: csurf (or modern alternatives like csrf-csrf)
CSRF middleware generates and validates per-session tokens to ensure requests originate from your own forms.
Question 5: Where should error-handling middleware be placed in an Express application?
- After all other app.use() and route definitions (Correct answer)
- Inside route handlers only
- At any position
- Before all routes
Correct answer: After all other app.use() and route definitions
Error-handling middleware must be defined last so it can catch errors passed via next(err) from all prior middleware and routes.
Question 6: How do you pass a custom error to the Express error handler from a route?
- next(new Error('message')) (Correct answer)
- res.error(new Error('message'))
- throw new Error('message')
- app.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 7: What HTTP header is conventionally used to send a JWT in an API request?
- X-Auth-Token: <token>
- Token: <token>
- Authorization: Bearer <token> (Correct answer)
- Auth: JWT <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 8: In Pug templates, which syntax adds a CSS class to a div element?
- div#highlight
- div(id=highlight)
- div.highlight (Correct answer)
- div[class=highlight]
Correct answer: div.highlight
Pug uses CSS selector-like shorthand where a period followed by the class name (div.highlight) adds a class attribute.
Question 9: Which Content Security Policy (CSP) header directive restricts which origins can load scripts?
- default-src
- frame-src
- connect-src
- script-src (Correct answer)
Correct answer: script-src
The script-src directive in a Content-Security-Policy header controls which sources are allowed to execute JavaScript.
Question 10: What is SQL injection and how do you prevent it in an Express app using a database?
- A type of CSRF attack
- A server misconfiguration issue
- Injecting SQL via HTTP headers only
- Malicious SQL in inputs; prevent by using parameterized queries or an ORM (Correct answer)
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 11: Root paths determine the endpoints at which requests can be made when used in conjunction with request methods. <br> Which of the following is a proper route path form?
- all of the above (Correct answer)
- string
- regular expressions
- string patterns
Correct answer: all of the above
Explanation: <br> All of the above are the proper route path forms.
Question 12: What is the purpose of input sanitization in an Express application?
- Removing or escaping dangerous characters from user input to prevent XSS and injection attacks (Correct answer)
- Validating data types only
- Compressing input data
- Formatting data for display
Correct answer: Removing or escaping dangerous characters from user input to prevent XSS and injection attacks
Sanitization strips or encodes malicious content from inputs, complementing validation to prevent injection and XSS vulnerabilities.
Question 13: Which header should an Express API set to indicate the response body format is JSON?
- Content-Type: application/json (Correct answer)
- Accept: application/json
- Response-Format: json
- X-Content-Type: json
Correct answer: Content-Type: application/json
The Content-Type header tells the client the media type of the response body; res.json() sets this automatically.
Question 14: Which approach correctly handles errors in Express async route handlers?
- Use async/await without try/catch
- Express automatically catches async errors
- Wrap in try/catch and call next(err) (Correct answer)
- Use Promise.resolve()
Correct answer: Wrap in try/catch and call next(err)
Async errors must be caught with try/catch and forwarded via next(err), or wrapped with an async error handler utility.
Question 15: Which Express method is used to register a custom or third-party template engine?
- app.engine() (Correct answer)
- app.set()
- app.register()
- app.use()
Correct answer: app.engine()
app.engine(ext, callback) maps a file extension to a render function, allowing Express to use any compliant template engine.
Question 16: In Express, what regular expression pattern matches routes like /ab?cd?
- The 'b' and 'd' characters are optional (Correct answer)
- The 'a' and 'c' characters are optional
- The entire path is optional
- The path requires exactly one of each character
Correct answer: The 'b' and 'd' characters are optional
In Express route patterns, '?' makes the preceding character optional, so /ab?cd matches /acd and /abcd.
Question 17: What is res.locals used for in Express template rendering?
- Specifying which template engine to use for a single response
- Storing variables available to templates for the current request only (Correct answer)
- Caching previously rendered views
- Setting global app-level variables shared across all requests
Correct answer: Storing variables available to templates for the current request only
res.locals is request-scoped; properties set on it are available to templates rendered during that request/response cycle only.
Question 18: How can you define multiple callback functions for a single route in Express?
- Use app.chain()
- Use app.multi()
- Pass them as multiple arguments or an array to app.get() (Correct answer)
- Nest route definitions
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 19: How do you force a file download response (with Content-Disposition attachment) in Express?
- res.sendFile(filePath, { attachment: true })
- res.attach(filePath)
- res.file(filePath, 'download')
- res.download(filePath) (Correct answer)
Correct answer: res.download(filePath)
res.download() transfers a file and sets Content-Disposition to 'attachment', prompting the browser to download it.
Question 20: How do you verify a JWT in an Express middleware using the jsonwebtoken package?
- jwt.authenticate(token, secret)
- jwt.decode(token, secret)
- jwt.verify(token, secret, callback) (Correct answer)
- jwt.check(token, secret)
Correct answer: jwt.verify(token, secret, callback)
jwt.verify() validates the token's signature and expiration, returning the decoded payload if valid.
Question 21: How do you mount a router module at the path '/api' in Express?
- app.attach('/api', router)
- app.route('/api', router)
- app.use('/api', router) (Correct answer)
- app.mount('/api', router)
Correct answer: app.use('/api', router)
app.use() mounts middleware or a router at a specified path prefix.
Question 22: How can you create a custom error class with an HTTP status code for use with Express?
- Use express.HttpError()
- Use the http-errors package only
- Extend Error and add a status property (Correct answer)
- Configure errors in app.settings
Correct answer: Extend Error and add a status property
You can extend the built-in Error class and attach a status property to carry HTTP status codes through the error pipeline.
Question 23: What is the primary purpose of JSON Web Tokens (JWT) in an Express application?
- Stateless authentication by encoding user identity in a signed token (Correct answer)
- Compressing JSON payloads
- Encrypting database connections
- Storing session data server-side
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 24: Which Express object is used to create a modular, mountable route handler?
- express.Router() (Correct answer)
- express.Handler()
- express.Module()
- express.Route()
Correct answer: express.Router()
express.Router() creates a mini-application capable of performing middleware and routing functions.
Question 25: In terms of route parameters, where are the captured values populated?
- req.params (Correct answer)
- req.data
- All of the above
- app.locals
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 26: What does app.locals do in the context of Express templates?
- Registers a custom template engine
- Enables view caching in production
- Defines variables accessible to all templates across all requests (Correct answer)
- Sets the views directory path
Correct answer: Defines variables accessible to all templates across all requests
app.locals properties are merged into res.locals for every request, making them available as variables in every rendered template.
Question 27: Which object's properties are automatically merged and available as local variables in all rendered templates?
- req.locals
- app.locals (Correct answer)
- res.session
- process.env
Correct answer: app.locals
app.locals properties are merged with res.locals before template rendering, making them globally available across all views in the application.
Question 28: What does express.Router() return?
- An HTTP server
- A middleware array
- The main app object
- A mini Express application / isolated router instance (Correct answer)
Correct answer: A mini Express application / isolated router instance
express.Router() returns an isolated router instance that acts like a mini-app with its own middleware and routes.
Question 29: What does the next() function do inside an Express route handler?
- Redirects to the next URL
- Passes control to the next matching middleware or route (Correct answer)
- Ends the request-response cycle
- Sends the response to the client
Correct answer: Passes control to the next matching middleware or route
Calling next() passes control to the next middleware function in the stack.
Question 30: Which template engine uses indentation-based whitespace-sensitive syntax instead of traditional HTML closing tags?
- EJS
- Pug (Correct answer)
- Mustache
- Handlebars
Correct answer: Pug
Pug uses significant indentation to define element nesting, eliminating the need for closing tags and angle brackets entirely.
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