NormalizePath class final

Makes /todos and /todos/ mean the same thing.

The router treats them as different paths on purpose — a route table that silently matched both would hide a duplicate. This layer decides the question once, at the edge, instead of every route declaring itself twice.

final app = Router()
  ..layer(const NormalizePath())
  ..merge(routes);

Two ways to settle it, and the choice is not cosmetic:

  • Rewrite (the default) serves the normalized path directly. One request, one response, and the URL in the address bar is left alone.
  • Redirect answers 308 and sends the client to the canonical form. It costs a round trip and it collapses two URLs into one for caches, logs, and search engines — which is the reason to pay for it.

The root path is never touched: / is already canonical, and stripping its slash would leave an empty path nothing can match.

A layer covers everything the router it is on answers, 404s included, so this works at the top level or scoped to a prefix:

// The whole application.
final app = Router()
  ..layer(const NormalizePath())
  ..nest('/api', api);

// Only `/api`. Useful when the other half has URLs you must not rewrite —
// a webhook whose signature covers the exact path, say.
final api = Router()
  ..layer(const NormalizePath())
  ..route('/notes', get(listNotes));
Implemented types

Constructors

NormalizePath({TrailingSlash slash = TrailingSlash.strip})
Normalizes by rewriting the request.
const
NormalizePath.redirecting({TrailingSlash slash = TrailingSlash.strip})
Normalizes by redirecting the client to the canonical form.
const

Properties

hashCode int
The hash code for this object.
no setterinherited
redirect bool
Whether to redirect rather than rewrite.
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
slash TrailingSlash
Which form is canonical.
final

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toMiddleware() Middleware
Builds the shelf middleware this value configures.
override
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited