-
Notifications
You must be signed in to change notification settings - Fork 2
/
next.ts
48 lines (39 loc) · 1.71 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
45
46
47
48
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;
mode?: "full" | "light";
logged?: boolean;
};
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 } : {}),
mode: config.mode ?? "full",
logged: config.logged ?? true,
});
return async (req: NextRequest, context: NextFetchEvent) => {
const response = await edgeMiddleware(req, context);
return new NextResponse(response.body, response);
};
};