next-wayfinder
Version:
Apply multiple next.js middlewares with ease
65 lines (62 loc) • 2.01 kB
TypeScript
import { NextRequest, NextMiddleware } from 'next/server';
import { Middleware, RequestInjector, BeforeAllMiddleware, RequestParser, ResponseFactory } from './types.js';
export { NextMiddlewareWithParams, NextRequestWithParams } from './types.js';
import 'path-to-regexp';
interface WayfinderOptions<T> {
debug?: boolean;
/**
*
* A function that returns the data to be injected into the request
*/
context?: RequestInjector<T> | T;
/**
* Global middleware to be executed before all other middlewares
* Useful if you want to set a cookie or apply some logic before each request
*/
beforeAll?: BeforeAllMiddleware;
/**
*
* A function to extract `hostname` and `pathname` from `NextRequest`
*/
parser?: RequestParser;
/**
* The response to be used.
* Useful when you want to chain other middlewares or return a custom response
* Default to `NextResponse.next()`
*/
response?: ResponseFactory;
}
declare const getHost: (request: NextRequest) => string;
/**
*
* A function that filters the requests based on the path or hostname
* and then executes the corresponding middleware or middlewares
*
* @param middlewares {Middleware} - An array of middlewares
* @param options {WayfinderOptions} - An object containing the options
*
* @returns {NextMiddleware} - A NextMiddleware function
*
* @example
* ```ts
* import { handlePaths } from "next-wayfinder";
*
* export default handlePaths([
* {
* path: "/dashboard/:path",
* handler: async (req, ev) => {
* const isAuthorized = await checkAuthorization(req);
*
* if (!isAuthorized) {
* return NextResponse.redirect("/login");
* }
*
* return NextResponse.next();
* },
* }
*]);
* ```
*
*/
declare function handlePaths<T>(middlewares: Middleware<T>[], { response: res, ...options }?: WayfinderOptions<T>): NextMiddleware;
export { Middleware, getHost, handlePaths };