Comments (// and /* */)
Express runs on Node.js, so its comment syntax is the same as JavaScript. Single-line comments (//), block comments (/* */), and JSDoc comments (/** */) are all available. A common Express-specific convention is to write the HTTP method, path, and a brief description of the handler in a comment immediately before each route handler.
Syntax
// Single-line comment — everything from // to the end of the line is a comment.
const port = 3000; // Port number the server listens on
/*
Block comment — everything between /* and */ is a comment.
Use this when you want to write a comment that spans multiple lines.
*/
/**
* JSDoc comment — a block comment that starts with /**.
* Write this immediately before a middleware function or route handler.
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {import('express').NextFunction} next - Function to call the next middleware
*/
Comment Types
| Type | Syntax | Description |
|---|---|---|
| Single-line comment | // text | Everything from // to the end of the line becomes a comment. Also used to add a note to the right of a line of code. |
| Block comment | /* text */ | Used when writing a comment that spans multiple lines. Often used for route group descriptions or file-level overviews. |
| JSDoc comment | /** text */ | A special block comment starting with /**. Written immediately before a middleware function or route handler to document types and descriptions in a format that editors and automatic documentation tools can parse. |
Common JSDoc Tags
Writing JSDoc comments on Express middleware functions and route handlers causes editors such as VS Code to display documentation on hover. Documenting the types and roles of parameters in shared middleware and reusable handler functions reduces the cost of looking up documentation.
| Tag | Description |
|---|---|
| @param {type} name - description | Documents the type and description of a function parameter. In Express, the types of req, res, and next are often specified using import notation. |
| @returns {type} description | Documents the type and description of a function's return value. |
| @throws ErrorType - description | Documents exceptions that may be thrown. |
| @middleware | Not a standard JSDoc tag, but sometimes written in comments to explicitly indicate that a function is a middleware. |
| @route method path | Not a standard JSDoc tag, but sometimes written in comments to explicitly indicate the HTTP method and path of a route handler. |
| @deprecated reason | Marks something as deprecated and provides a reason. Editors display a warning. |
Route Handler Comment Convention
In Express route files, a common pattern is to write the HTTP method, path, and a brief description as a comment immediately before each route handler. This convention lets you scan a route file and get an overview of the API endpoints.
// GET /users — Returns a list of all users.
app.get('/users', function(req, res) { /* ... */ });
// POST /users — Creates a new user. Requires name and email in the request body.
app.post('/users', function(req, res) { /* ... */ });
// GET /users/:id — Returns the user with the given ID. Returns 404 if not found.
app.get('/users/:id', function(req, res) { /* ... */ });
// DELETE /users/:id — Deletes the user with the given ID. Requires authentication.
app.delete('/users/:id', authenticateMiddleware, function(req, res) { /* ... */ });
When to Write Comments and When Not To
| Decision | Situation | Reason |
|---|---|---|
| Write a comment | The reason why something was implemented a certain way | Design decisions and trade-offs that cannot be understood from the code alone help your future self and other developers. |
| Write a comment | Complex algorithms or formulas | Add a brief description of what a piece of logic does when its behavior is not immediately obvious at a glance. |
| Write a comment | Middleware and reusable functions | Documenting parameters, return values, and side effects with JSDoc lets callers use them without consulting external documentation. |
| Write a comment | Temporarily disabled code during debugging | Leaving a note explaining why code was commented out reduces the risk of forgetting to clean it up later. |
| No comment needed | Logic that is obvious from reading the code | Obvious comments become noise. Clear variable and function names remove the need for such comments. |
| No comment needed | Change history or deleted code | Because version control (git) is available, there is no need to keep old code or change dates in comments. |
Sample Code
Route File with Comments
routes/users.js
var express = require('express');
var router = express.Router();
/*
File containing user-related routes.
Routes requiring authentication have authenticateMiddleware applied first.
*/
/**
* Middleware that checks whether the request includes a token.
* Returns 401 if the token is missing or invalid.
* @param {import('express').Request} req
* @param {import('express').Response} res
* @param {import('express').NextFunction} next
*/
function authenticateMiddleware(req, res, next) {
var token = req.headers['authorization'];
if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}
// TODO: add actual JWT verification logic here (see #45).
next();
}
// GET /users — Returns a list of all users.
router.get('/', function(req, res) {
// Dummy data. In practice, retrieved from the database.
var users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
];
res.json(users);
});
// GET /users/:id — Returns the user with the given ID.
router.get('/:id', function(req, res) {
var id = parseInt(req.params.id, 10);
/*
The radix 10 is passed to parseInt to prevent strings like '08'
from being interpreted as octal numbers.
*/
if (isNaN(id)) {
return res.status(400).json({ error: 'Invalid ID' });
}
// Returns a dummy user with ID 1.
if (id === 1) {
return res.json({ id: 1, name: 'Alice', email: 'alice@example.com' });
}
res.status(404).json({ error: 'User not found' });
});
// POST /users — Creates a new user. Requires authentication.
router.post('/', authenticateMiddleware, function(req, res) {
var name = req.body.name;
var email = req.body.email;
if (!name || !email) {
// Required fields are missing from the request body.
return res.status(400).json({ error: 'name and email are required' });
}
// Debug: verify received data (remove in production).
// console.log('Creating user:', { name, email });
res.status(201).json({ id: 3, name: name, email: email });
});
module.exports = router;
app.js
var express = require('express');
var app = express();
/* Register middleware to parse JSON request bodies. */
app.use(express.json());
// Mount the user routes at the /users path.
var usersRouter = require('./routes/users');
app.use('/users', usersRouter);
/*
Error-handling middleware is a function with four arguments (err, req, res, next).
The number of arguments is important to distinguish it from regular middleware.
*/
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).json({ error: 'Internal Server Error' });
});
var PORT = 3000;
app.listen(PORT, function() {
console.log('Server running on port ' + PORT);
});
Overview
Express comment syntax is the same as Node.js / JavaScript. Single-line comments (//), block comments (/* */), and JSDoc comments (/** */) are used. An Express-specific convention is to write the HTTP method and path in a comment immediately before each route handler, making it easy to scan a route file and understand the API endpoints at a glance.
Writing JSDoc comments on shared middleware and reusable utility functions causes VS Code to display parameter types and descriptions on hover. Explicitly documenting the types of req, res, and next improves code completion even in projects that do not use TypeScript.
Comments are most effective when they explain "why" rather than "what." Commenting on every piece of logic that is already obvious from the code itself becomes noise. There is also no need to keep change history or deleted code in comments — those are tracked by version control (git).
If you find any errors or copyright issues, please contact us.