Koa Path Canonicalizer Middleware
raw JSON →koa-path-canonicalizer is a Koa middleware designed to automatically redirect incoming requests to a canonicalized path. This typically involves normalizing URL structures, such as ensuring consistent trailing slashes or removing duplicate slashes, which helps improve SEO by preventing duplicate content issues and maintaining clean URLs. The package is currently at version 0.2.0, indicating it's still in early development stages, with a relatively stable and slow release cadence, having had only two minor releases since its initial launch. Its key differentiator is its focused and straightforward integration into Koa applications for basic path normalization, offering a minimalist solution without extensive configuration overhead compared to broader routing libraries.
Common errors
error Error: Can't set headers after they are sent. ↓
koa-path-canonicalizer is mounted early in your Koa middleware chain, typically before any middleware that might send a response or perform its own redirects based on the original path. error TypeError: (0 , _koaPathCanonicalizer.pathCanonicalizer) is not a function ↓
import pathCanonicalizer from 'koa-path-canonicalizer'; to import { pathCanonicalizer } from 'koa-path-canonicalizer';. error ERR_TOO_MANY_REDIRECTS ↓
koa-path-canonicalizer's trailingSlash option explicitly (true or false) to match the desired canonical form and avoid conflicts. Warnings
gotcha The default behavior of `koa-path-canonicalizer` for trailing slashes might not align with all application requirements. By default, it removes trailing slashes. If your application expects or requires trailing slashes, you must explicitly configure the `trailingSlash` option. ↓
gotcha When deployed behind reverse proxies or load balancers, `koa-path-canonicalizer` might generate incorrect redirect URLs if the `X-Forwarded-Proto` or `X-Forwarded-Host` headers are not correctly processed by Koa's `ctx.url` or `ctx.href`. This can lead to redirects pointing to `http` instead of `https`, or an incorrect domain. ↓
gotcha Combining `koa-path-canonicalizer` with other path-manipulating middleware (e.g., custom redirect logic, other routing middleware that modifies `ctx.path`) can lead to infinite redirect loops. Ensure only one piece of middleware is responsible for canonicalizing paths. ↓
Install
npm install koa-path-canonicalizer yarn add koa-path-canonicalizer pnpm add koa-path-canonicalizer Imports
- pathCanonicalizer wrong
import pathCanonicalizer from 'koa-path-canonicalizer';correctimport { pathCanonicalizer } from 'koa-path-canonicalizer'; - pathCanonicalizer (CommonJS) wrong
const pathCanonicalizer = require('koa-path-canonicalizer');correctconst { pathCanonicalizer } = require('koa-path-canonicalizer'); - Options (TypeScript)
import type { Options } from 'koa-path-canonicalizer';
Quickstart
import Koa from 'koa';
import { pathCanonicalizer } from 'koa-path-canonicalizer';
const app = new Koa();
// Apply the canonicalizer middleware early in the chain.
// By default, it removes trailing slashes and normalizes multiple slashes.
app.use(pathCanonicalizer({
trailingSlash: false, // Ensures no trailing slash (e.g., /foo/ -> /foo)
normalizeMultiSlashes: true // Ensures //foo/bar -> /foo/bar
}));
// Example route to demonstrate functionality
app.use(async (ctx, next) => {
if (ctx.path === '/') {
ctx.body = 'Welcome to the homepage!';
} else if (ctx.path === '/hello') {
ctx.body = `Hello from ${ctx.path}! Try navigating to /hello/ or //hello.`;
} else {
ctx.body = `You are at ${ctx.path}`;
}
await next();
});
const PORT = process.env.PORT ?? 3000;
app.listen(PORT, () => {
console.log(`Koa server running on http://localhost:${PORT}`);
console.log('Try visiting:');
console.log(`- http://localhost:${PORT}/hello/ (should redirect to /hello)`);
console.log(`- http://localhost:${PORT}///hello (should redirect to /hello)`);
});