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.
npm install express-slashVerified import paths — ran on the pinned version, not inferred.
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.
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.
Ensure your `app.use(slash())` call appears *after* `app.use(router)` or any other route-defining middleware.
Add `app.enable('strict routing');` early in your Express application setup.When creating a router, pass the `strict` option: `const router = express.Router({ strict: app.get('strict routing') });`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.
Always call `express-slash` as a function: `app.use(slash());`
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')`.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.