forked from redirectionio/vercel-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
next.ts
44 lines (35 loc) · 1.59 KB
/
next.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
import { createRedirectionIoMiddleware as createEdgeMiddleware } from "./middleware";
import { RequestContext } from "@vercel/edge";
type Middleware = (request: NextRequest, context: NextFetchEvent) => NextResponse | Promise<NextResponse>;
type CreateMiddlewareConfig = {
previousMiddleware?: Middleware;
nextMiddleware?: Middleware;
matcherRegex?: string | null;
};
export const createRedirectionIoMiddleware = (config: CreateMiddlewareConfig): Middleware => {
let previousMiddleware;
let nextMiddleware;
const configPreviousMiddleware = config.previousMiddleware;
const configNextMiddleware = config.nextMiddleware;
const configMatcherRegex = config.matcherRegex;
if (configPreviousMiddleware) {
previousMiddleware = (req: Request, context: RequestContext) => {
return configPreviousMiddleware(new NextRequest(req.url, req), context as any as NextFetchEvent);
};
}
if (configNextMiddleware) {
nextMiddleware = (req: Request, context: RequestContext) => {
return configNextMiddleware(new NextRequest(req.url, req), context as any as NextFetchEvent);
};
}
const edgeMiddleware = createEdgeMiddleware({
previousMiddleware,
nextMiddleware,
...(configMatcherRegex ? { matcherRegex: configMatcherRegex } : {}),
});
return async (req: NextRequest, context: NextFetchEvent) => {
const response = await edgeMiddleware(req, context);
return new NextResponse(response.body, response);
};
};