HackerRank Express.js Skills Certification β Questions and Answers
Question 1: What does app.locals do in the context of Express templates?
- Registers a custom template engine
- Sets the views directory path
- Enables view caching in production
- Defines variables accessible to all templates across all requests (Correct answer)
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 2: How do you retrieve the value of the 'Authorization' request header in Express?
- req.getHeader('Authorization')
- req.headers.Authorization
- req.get('Authorization') or req.headers['authorization'] (Correct answer)
- req.header.Authorization
Correct answer: req.get('Authorization') or req.headers['authorization']
req.get() retrieves a request header case-insensitively, or you can access req.headers directly using lowercase keys.
Question 3: Cookies are huge, complicated files/data that are transmitted to the server with a client request and stored on the server.
- Cannot say
- This statement is false (Correct answer)
- It can be true or false
- This statement is true
Correct answer: This statement is false
Explanation: <br> Cookies are tiny files/data delivered to the client as part of a server request and kept on the client's computer. As a result, the statement in the question is incorrect.
Question 4: How do you define a catch-all route that handles any path not matched by previous routes?
- app.fallback(handler)
- app.use('*', handler) or app.get('*', handler) placed last (Correct answer)
- app.default(handler)
- app.catch(handler)
Correct answer: app.use('*', handler) or app.get('*', handler) placed last
Placing a wildcard route or middleware at the end of all routes catches any unmatched requests.
Question 5: Which Content Security Policy (CSP) header directive restricts which origins can load scripts?
- script-src (Correct answer)
- default-src
- frame-src
- connect-src
Correct answer: script-src
The script-src directive in a Content-Security-Policy header controls which sources are allowed to execute JavaScript.
Question 6: In Express, where must error-handling middleware be placed relative to other middleware?
- At the beginning, before routes
- Inside individual route handlers
- At the very end, after all routes and other middleware (Correct answer)
- Anywhere in the stack
Correct answer: At the very end, after all routes and other middleware
Error-handling middleware must be the last middleware registered so it can intercept errors from all prior handlers.
Question 7: How do you implement rate limiting in an Express REST API?
- Use express-rate-limit middleware to restrict requests per IP in a time window (Correct answer)
- Use app.throttle()
- Set limits in the nginx configuration only
- Use built-in Express rate limiting
Correct answer: Use express-rate-limit middleware to restrict requests per IP in a time window
express-rate-limit is the standard middleware for capping requests per IP over a configurable time window.
Question 8: What does the helmet package help protect against in Express?
- CSRF only
- Brute-force login attempts
- XSS, clickjacking, and other attacks by setting security HTTP headers (Correct answer)
- SQL injection
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 9: How can you create a custom error class with an HTTP status code for use with Express?
- Use express.HttpError()
- Configure errors in app.settings
- Extend Error and add a status property (Correct answer)
- Use the http-errors package only
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 10: What happens when you pass a string pattern '/ab*cd' as an Express route path?
- It throws a syntax error
- It matches any path starting with /ab
- It matches /abcd, /abXcd, /ab123cd, etc. (Correct answer)
- It only matches /abcd exactly
Correct answer: It matches /abcd, /abXcd, /ab123cd, etc.
The '*' wildcard in an Express route pattern matches any sequence of characters.
Question 11: Which property of the request object contains the query string parameters parsed as an object?
- req.qs
- req.query (Correct answer)
- req.params
- req.search
Correct answer: req.query
req.query contains the parsed query string as a key-value object.
Question 12: Which method sets the HTTP status code of a response in Express?
- res.httpStatus(code)
- res.status(code) (Correct answer)
- res.code(code)
- res.setStatus(code)
Correct answer: res.status(code)
res.status() sets the HTTP status code for the response and returns the response object for chaining.
Question 13: How do you apply middleware only to a specific router in Express?
- Use app.only()
- Pass it as the first argument to app.listen()
- Register it with router.use() on that router instance (Correct answer)
- Set middleware.scope = 'router'
Correct answer: Register it with router.use() on that router instance
router.use() scopes middleware to only the routes handled by that specific router instance.
Question 14: Which built-in Express middleware parses incoming JSON request bodies?
- express.json() (Correct answer)
- express.body()
- express.bodyParser()
- express.parseJSON()
Correct answer: express.json()
express.json() is the built-in middleware that parses incoming requests with JSON payloads.
Question 15: How do you validate request body data in an Express REST API?
- Validate inside the database layer only
- Rely on TypeScript types at runtime
- Use built-in Express validation
- Use validation middleware like express-validator or joi before the route handler (Correct answer)
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 16: What is the purpose of input sanitization in an Express application?
- Validating data types only
- Formatting data for display
- Compressing input data
- Removing or escaping dangerous characters from user input to prevent XSS and injection attacks (Correct answer)
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 17: What built-in Express middleware serves a directory listing or static files from a path?
- express.serve()
- express.directory()
- express.static() (Correct answer)
- express.files()
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 18: How do you differentiate between development and production error responses in Express?
- Check process.env.NODE_ENV in the error handler and conditionally include stack traces (Correct answer)
- Use NODE_ENV-specific route files
- Use app.set('env', 'production')
- Use different app instances per environment
Correct answer: Check process.env.NODE_ENV in the error handler and conditionally include stack traces
By checking process.env.NODE_ENV, you can expose detailed stack traces in development while sending minimal info in production.
Question 19: What is SQL injection and how do you prevent it in an Express app using a database?
- A server misconfiguration issue
- Malicious SQL in inputs; prevent by using parameterized queries or an ORM (Correct answer)
- A type of CSRF attack
- 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 20: What HTTP status code should be returned for validation errors on user input in an Express API?
- 403 Forbidden
- 422 Unprocessable Entity or 400 Bad Request (Correct answer)
- 400 Bad Request
- 500 Internal Server Error
Correct answer: 422 Unprocessable Entity or 400 Bad Request
Both 400 Bad Request and 422 Unprocessable Entity are appropriate for validation failures; 422 is more semantically precise.
Question 21: 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
- express-validator
- cors
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 22: Which built-in Express middleware parses URL-encoded form data?
- express.formData()
- express.form()
- express.parseForm()
- express.urlencoded() (Correct answer)
Correct answer: express.urlencoded()
express.urlencoded() parses incoming requests with URL-encoded payloads, such as HTML form submissions.
Question 23: How do you implement content negotiation in an Express API?
- Check Content-Type only
- Use req.accepts() to check the Accept header and respond with the matching format (Correct answer)
- Use req.format()
- Use a format query parameter exclusively
Correct answer: Use req.accepts() to check the Accept header and respond with the matching format
req.accepts() checks the Accept header and returns the best matching content type, allowing the API to serve JSON, XML, etc.
Question 24: What is the primary purpose of JSON Web Tokens (JWT) in an Express application?
- Storing session data server-side
- Stateless authentication by encoding user identity in a signed token (Correct answer)
- Compressing JSON payloads
- Encrypting database connections
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 25: Which template engine uses indentation-based whitespace-sensitive syntax instead of traditional HTML closing tags?
- EJS
- Pug (Correct answer)
- Handlebars
- Mustache
Correct answer: Pug
Pug uses significant indentation to define element nesting, eliminating the need for closing tags and angle brackets entirely.
Question 26: How do you set a response header in Express?
- res.header['Header-Name'] = 'value'
- res.addHeader('Header-Name', 'value')
- res.set('Header-Name', 'value') or res.setHeader() (Correct answer)
- res.headers.push()
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: In Pug templates, which keyword includes another Pug file into the current template?
- import
- include (Correct answer)
- extend
- require
Correct answer: include
The 'include' keyword in Pug inserts the contents of another template file at that position, enabling template composition.
Question 28: How do you force a file download response (with Content-Disposition attachment) in Express?
- res.file(filePath, 'download')
- res.attach(filePath)
- res.sendFile(filePath, { attachment: true })
- 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 29: What is the default HTTP status code Express sends if an error reaches the error handler without res.status() being set?
- 400
- 503
- 500 (Correct answer)
- 404
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 30: What is the purpose of bcrypt when handling passwords in an Express application?
- Validating password format
- Encrypting passwords for transmission
- Generating JWT secrets
- Hashing passwords with a salt to securely store them (Correct answer)
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 31: How do you access a route parameter named 'userId' in an Express handler?
- req.params.userId (Correct answer)
- req.query.userId
- req.id.userId
- req.body.userId
Correct answer: req.params.userId
Named route parameters are available on the req.params object.
Question 32: What is route chaining in Express?
- Connecting multiple apps together
- Using nested route parameters
- Using app.route() to chain multiple HTTP method handlers for one path (Correct answer)
- Linking routes across different files
Correct answer: Using app.route() to chain multiple HTTP method handlers for one path
app.route() returns a route instance that allows chaining handlers for GET, POST, PUT, etc. on the same path.
Question 33: What is the role of CORS in an Express API security context?
- Prevents SQL injection
- Controls which origins are allowed to make cross-origin requests to the API (Correct answer)
- Encrypts API traffic
- Validates API keys
Correct answer: Controls which origins are allowed to make cross-origin requests to the API
CORS headers restrict which web origins can call your API, preventing unauthorized cross-origin JavaScript from making API requests.
Question 34: In EJS, which tag outputs raw unescaped HTML directly into the page?
- <% %>
- <%= %>
- <%- %> (Correct answer)
- <%+ %>
Correct answer: <%- %>
<%- %> outputs the value without HTML escaping, which is useful for rendering pre-sanitized HTML content.
Question 35: What are the three arguments a standard Express middleware function receives?
- request, response, callback
- req, next, done
- req, res, next (Correct answer)
- req, res, err
Correct answer: req, res, next
Standard Express middleware receives the request object (req), response object (res), and the next() function.
Question 36: To check the current version of NPM, which of the following commands is used?
- npm help
- nmp --ver
- None of the above.
- npm --version (Correct answer)
Correct answer: npm --version
Explanation: <br> The command npm βversion or npm -v from your terminal is the quickest way to see what version of npm is installed on your machine. This npm β version command also displays additional information on the npm version, as well as the node version, v8 version, OpenSSL version, and many other packages.
Question 37: How do you pass dynamic data to a template when calling res.render()?
- res.render('view', { key: value }) (Correct answer)
- res.data = { key: value }; res.render('view')
- req.locals = { key: value }; res.render('view')
- app.data({ key: value }); res.render('view')
Correct answer: res.render('view', { key: value })
res.render() accepts a view name as the first argument and an optional plain object of local variables as the second argument.
Question 38: Which HTTP method does app.delete() handle in Express?
- ERASE
- DESTROY
- REMOVE
- DELETE (Correct answer)
Correct answer: DELETE
app.delete() registers a route handler for the HTTP DELETE method.
Question 39: What property on an error object does Express use to set the response status code in the default error handler?
- err.code
- err.status or err.statusCode (Correct answer)
- err.responseCode
- err.httpCode
Correct answer: err.status or err.statusCode
Express's default error handler reads err.status or err.statusCode to determine the HTTP response status.
Question 40: How should an Express REST API communicate available API endpoints to consumers?
- Only via internal documentation
- Provide an OpenAPI/Swagger specification document (Correct answer)
- Use HTTP OPTIONS responses exclusively
- Write a plain-text README only
Correct answer: Provide an OpenAPI/Swagger specification document
OpenAPI (Swagger) specifications provide a machine-readable, standardized description of all API endpoints, parameters, and responses.
Question 41: What is the purpose of router.param() in Express?
- Adds a callback triggered when a specific route parameter is present (Correct answer)
- Sets default parameter values
- Defines optional route segments
- Validates query parameters
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 42: Which package is commonly used to implement Passport.js-based authentication in Express?
- passport (Correct answer)
- auth-middleware
- express-auth
- express-passport
Correct answer: passport
passport is the widely-used authentication middleware for Express that supports hundreds of strategies including local, OAuth, and JWT.
Question 43: How does the express-session middleware store session data by default?
- In a database automatically
- In a cookie on the client
- In-memory on the server (not suitable for production) (Correct answer)
- In the file system
Correct answer: In-memory on the server (not suitable for production)
The default MemoryStore is in-process memory storage, which doesn't scale and leaks memory β use a persistent store in production.
Question 44: How many parameters must an Express error-handling middleware function declare?
- 2 (err, next)
- 3 (err, req, res)
- 5 (err, req, res, next, app)
- 4 (err, req, res, next) (Correct answer)
Correct answer: 4 (err, req, res, next)
Express identifies error-handling middleware by its four-parameter signature: err, req, res, and next.
Question 45: What is the recommended way to handle async errors in Express 5?
- Express 5 automatically catches rejected promises in route handlers (Correct answer)
- Use synchronous code only
- Use a global unhandledRejection listener
- Manually wrap every route in try/catch
Correct answer: Express 5 automatically catches rejected promises in route handlers
Express 5 natively handles rejected promises in route handlers and middleware, automatically forwarding them to error handlers.
Question 46: What does HATEOAS stand for and how does it relate to Express REST APIs?
- Hyperlink Access To External API Schemas
- HTML And Text Engine Of Application Services
- Hypermedia As The Engine Of Application State β including links in responses to guide clients (Correct answer)
- HTTP Access To External Object Storage
Correct answer: Hypermedia As The Engine Of Application State β including links in responses to guide clients
HATEOAS is a REST constraint where responses include links that describe available next actions, making APIs self-discoverable.
Question 47: What does the secure: true option do when setting cookies in Express?
- Sets a short expiration time
- Ensures the cookie is only sent over HTTPS connections (Correct answer)
- Encrypts the cookie value
- Prevents the cookie from being accessed by scripts
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 48: In Express routing, what does the path '/' represent?
- An empty path only
- The root path of the application or mounted router (Correct answer)
- A relative path placeholder
- Any path
Correct answer: The root path of the application or mounted router
The path '/' refers to the root of the application or the mount point if it's a sub-router.
Question 49: Which of the following was the Pug's previous name?
- DRY
- Terse
- Express
- Jade (Correct answer)
Correct answer: Jade
Explanation: <br> Jade was Pug's previous name. It's a succinct programming language for creating HTML templates.
Question 50: In Pug templates, which syntax adds a CSS class to a div element?
- div.highlight (Correct answer)
- div#highlight
- div[class=highlight]
- div(id=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.
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