connect-slashes
raw JSON → 1.4.0 verified Sat Apr 25 auth: no javascript
Trailing slash redirect middleware for Connect and Express.js. Version 1.4.0 is the current stable release, with no predictable cadence. It automatically appends or removes trailing slashes from URLs to enforce canonical URLs. Unlike alternatives like `express-slash`, it uses 301 redirects by default and supports custom base paths and headers. It only affects GET, HEAD, and OPTIONS requests to avoid data loss on POST/PUT.
Common errors
error Cannot find module 'connect-slashes' ↓
cause Package not installed or not in node_modules.
fix
Run
npm install connect-slashes in your project directory. error TypeError: slashes is not a function ↓
cause Importing incorrectly, e.g., using named import when default export is used.
fix
Use
import slashes from 'connect-slashes' or const slashes = require('connect-slashes'). error 404 on static files after adding slashes middleware ↓
cause Middleware applied before static middleware, causing trailing slash to be appended to file URLs.
fix
Move slashes middleware after static middleware in the middleware stack.
Warnings
gotcha Middleware must be placed after connect.static() to avoid breaking static file URLs (e.g., /app.css becomes /app.css/). ↓
fix Order middleware correctly: static first, then slashes.
gotcha Only GET, HEAD, and OPTIONS requests are redirected. POST/PUT requests are unaffected. ↓
fix This is intentional; no fix needed.
gotcha Redirects default to 301 (permanent). Check if temporary redirects (302) are more appropriate for your use case. ↓
fix Pass { code: 302 } as second argument to slashes() for temporary redirects.
gotcha The `base` option prepends a base URL to the redirect path. Ensure it matches your reverse proxy configuration. ↓
fix Set the `base` option correctly, e.g., { base: '/blog' }.
Install
npm install connect-slashes yarn add connect-slashes pnpm add connect-slashes Imports
- default wrong
const slashes = require('connect-slashes')correctimport slashes from 'connect-slashes' - default (CommonJS) wrong
import { slashes } from 'connect-slashes'correctconst slashes = require('connect-slashes') - TypeScript usage wrong
import * as slashes from 'connect-slashes'correctimport slashes from 'connect-slashes'
Quickstart
const express = require('express');
const slashes = require('connect-slashes');
const app = express();
// Place after static middleware
app.use(express.static('public'));
app.use(slashes(true, { base: '/blog', code: 301, headers: { 'Cache-Control': 'public' } }));
app.get('/blog/post', (req, res) => res.send('Post'));
app.listen(3000);