Express Slash Middleware

raw JSON →
2.0.1 verified Thu Apr 23 auth: no javascript abandoned

express-slash is an Express.js middleware designed for web applications that enforce strict routing rules regarding trailing slashes in URLs. It automatically handles `GET` and `HEAD` requests, redirecting clients (with a 301 status code by default) to the canonical URL with or without a trailing slash, based on the application's configured routes and `strict routing` setting. This package ensures URL consistency and prevents 404 errors for users who might incorrectly add or omit trailing slashes. The current stable version is 2.0.1, specifically compatible with Express 4.x. Version 1.x was for Express 3.x. The package has not seen active development in many years, suggesting it is in an abandoned state. While alternatives exist, its direct integration with Express's `strict routing` is a key differentiator for maintaining consistent URL structures programmatically.

error TypeError: app.use() requires middleware functions but got a 'Object'
cause Attempting to use `express-slash` without calling it as a function, e.g., `app.use(slash);` instead of `app.use(slash());`
fix
Always call express-slash as a function: app.use(slash());
error Error: Cannot GET /path (and no redirection occurs)
cause The `express-slash` middleware is placed *before* the main Express router, or `app.enable('strict routing')` is not set, or the router itself doesn't have strict routing enabled.
fix
Ensure app.enable('strict routing'); is called, and app.use(slash()); comes *after* app.use(router);. Also, ensure strict is set to true when creating express.Router() instances if not inheriting from app.get('strict routing').
error Maximum call stack size exceeded / too many redirects
cause A redirection loop is occurring, often due to conflicting strict routing settings between the main app and a sub-router, or if `express-slash` is misconfigured with a wildcard route (e.g., `router.get('/:param/'`) where the middleware keeps toggling the slash.
fix
Verify that strict routing settings are consistent across app and all express.Router() instances. Ensure express-slash is placed correctly after routers and check for any routes that might conflict with its redirection logic, especially parameterized routes with optional trailing slashes.
breaking Breaking changes exist between major versions. `express-slash` v1.x is for Express 3.x, while v2.x is for Express 4.x. Using an incorrect version will lead to compatibility issues or runtime errors.
fix Ensure `express-slash` v2.x is used for Express 4.x applications. For Express 5.x, this package is not officially supported and may not function as expected due to changes in Express's routing. Consider alternative solutions for newer Express versions.
gotcha The `express-slash` middleware *must* be added after your application's `router` middleware. Placing it before the router will prevent it from correctly identifying and redirecting unmatched routes based on trailing slashes.
fix Ensure your `app.use(slash())` call appears *after* `app.use(router)` or any other route-defining middleware.
gotcha This middleware requires `app.enable('strict routing')` to be set in your Express application. Without strict routing, Express treats `/path` and `/path/` as the same, making `express-slash` ineffective for its intended purpose.
fix Add `app.enable('strict routing');` early in your Express application setup.
gotcha When using multiple routers or mounted paths, ensure that `strict routing` is also enabled on each `express.Router()` instance to prevent unexpected behavior or redirection loops. If a router is mounted with a trailing slash prefix (e.g., `app.use('/series/', seriesRouter)`), but the `seriesRouter` itself doesn't have strict routing enabled or has conflicting slash logic, it can lead to infinite redirects.
fix When creating a router, pass the `strict` option: `const router = express.Router({ strict: app.get('strict routing') });`
deprecated The `express-slash` package has not been updated in many years (last publish 12 years ago for version 2.0.1). While it works with Express 4.x, it is not maintained and is unlikely to be compatible with Express 5.x or future versions. Express 5.x itself has improved default handling for strict routing.
fix For new projects or migration to Express 5.x, consider leveraging Express's built-in `strict routing` options directly or exploring more actively maintained middleware alternatives for trailing slash management. Evaluate if `express-slash` is still necessary given Express 5.x's enhanced defaults and native support for features like async/await in middleware.
npm install express-slash
yarn add express-slash
pnpm add express-slash

This quickstart demonstrates how to set up `express-slash` with an Express application, enabling strict routing and ensuring proper trailing slash redirection for defined routes. It highlights the correct order of middleware.

const express = require('express');
const slash = require('express-slash');

const app = express();

// Important: Enable strict routing in Express for this middleware to be effective.
app.enable('strict routing');

// Create the router using the same routing options as the app.
const router = express.Router({
    caseSensitive: app.get('case sensitive routing'),
    strict       : app.get('strict routing')
});

// Define some routes. Note the trailing slash on '/about/'.
router.get('/', function (req, res) {
    res.send('Home Page');
});

router.get('/about/', function (req, res) {
    res.send('About Us');
});

router.get('/contact', function (req, res) {
    res.send('Contact Page');
});

// Add the `router` middleware first.
app.use(router);

// Add the `slash()` middleware *after* your app's `router`.
// Optionally specify an HTTP status code for redirection (defaults to 301).
app.use(slash());

const port = 3000;
app.listen(port, () => {
    console.log(`Server listening on http://localhost:${port}`);
    console.log(`Try http://localhost:${port}/about (will redirect to /about/)`);
    console.log(`Try http://localhost:${port}/contact/ (will redirect to /contact)`);
});