Koa Path Canonicalizer Middleware

raw JSON →
0.2.0 verified Thu Apr 23 auth: no javascript

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.

error Error: Can't set headers after they are sent.
cause Another middleware or route handler has already sent a response (e.g., `ctx.body = '...'`, `ctx.redirect()`) before `koa-path-canonicalizer` attempts to issue a redirect, leading to a conflict.
fix
Ensure 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
cause This error typically occurs in ESM contexts (e.g., TypeScript or modern Node.js) when attempting to use a default import for `koa-path-canonicalizer`, but the package only provides named exports.
fix
Change your import statement from import pathCanonicalizer from 'koa-path-canonicalizer'; to import { pathCanonicalizer } from 'koa-path-canonicalizer';.
error ERR_TOO_MANY_REDIRECTS
cause The browser or client reports too many redirects, indicating an infinite loop. This often happens when `koa-path-canonicalizer`'s redirection logic conflicts with another server configuration (e.g., a reverse proxy, web server rewrite rules) or another Koa middleware that also manipulates paths or performs redirects.
fix
Review all components in your request path (nginx, Apache, other Koa middleware) that might modify the URL. Configure koa-path-canonicalizer's trailingSlash option explicitly (true or false) to match the desired canonical form and avoid conflicts.
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.
fix Initialize the middleware with `pathCanonicalizer({ trailingSlash: true })` if you want to enforce trailing slashes, or `false` to enforce no trailing slashes.
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.
fix Ensure your Koa application is configured to trust proxy headers using `app.proxy = true;` and that your proxy correctly sets `X-Forwarded-For`, `X-Forwarded-Host`, and `X-Forwarded-Proto`.
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.
fix Place `koa-path-canonicalizer` early in your middleware chain and thoroughly test interactions with any other middleware that performs redirects or path rewrites. Configure options like `trailingSlash` to prevent conflicts with other components.
npm install koa-path-canonicalizer
yarn add koa-path-canonicalizer
pnpm add koa-path-canonicalizer

Demonstrates setting up a basic Koa application with `koa-path-canonicalizer` to automatically redirect requests to their canonicalized paths, showing how to remove trailing slashes and normalize multiple slashes.

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)`);
});