next-mw
Version:
A middleware manager for Next.js
86 lines (82 loc) • 2.5 kB
TypeScript
import { NextResponse, NextRequest, NextFetchEvent } from 'next/server';
/**
* Allowed literal types for matcher conditions.
*/
type AllowedMatcherType = 'header' | 'query' | 'cookie';
/**
* Matcher element type.
* It accepts either an object with a literal type (one of AllowedMatcherType)
* or an object with a general string, so that object literals without assertions work.
*/
type MatcherElement = {
type: AllowedMatcherType;
key: string;
value?: string;
} | {
type: string;
key: string;
value?: string;
};
/**
* Interface for a matcher condition object.
*/
interface MatcherCondition {
source: string;
regexp?: string;
locale?: boolean;
has?: MatcherElement[];
missing?: MatcherElement[];
}
/**
* Matcher can be a string, a MatcherCondition object, or an array of these.
*/
type Matcher = string | MatcherCondition | (string | MatcherCondition)[];
/**
* Type for a Next.js middleware result.
*/
type NextMiddlewareResult = NextResponse | Response | null | undefined | void;
/**
* Type for a Next.js middleware function.
*/
type NextMiddleware = (req: NextRequest, ev: NextFetchEvent) => NextMiddlewareResult | Promise<NextMiddlewareResult>;
/**
* Configuration option that uses only the "matcher" property.
*/
type ConfigMatcher = {
matcher: Matcher;
include?: never;
exclude?: never;
};
/**
* Configuration option that uses "include" and/or "exclude".
*/
type ConfigIncludeExclude = {
matcher?: never;
include?: Matcher;
exclude?: Matcher;
};
/**
* Configuration option type.
*/
type Config = ConfigMatcher | ConfigIncludeExclude;
/**
* Middleware module type.
* You can either use the "matcher" configuration
* or the "include"/"exclude" configuration, but not both.
*/
type MiddlewareModule = {
middleware: NextMiddleware;
config?: Config;
};
/**
* Composes multiple middlewares into a single middleware.
* Matching logic:
* - If "matcher" is defined, it is used exclusively.
* - Otherwise, if "include" is defined, the request must match at least one pattern.
* - And if "exclude" is defined, the request must not match any of the patterns.
*
* @param modules - List of imported middleware modules.
* @returns The composed middleware function.
*/
declare function middlewares(...modules: MiddlewareModule[]): NextMiddleware;
export { type Config, type ConfigIncludeExclude, type ConfigMatcher, type MiddlewareModule, type NextMiddleware, type NextMiddlewareResult, middlewares };