-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmiddleware.tsx
74 lines (68 loc) · 2.13 KB
/
middleware.tsx
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { NextResponse, NextRequest } from 'next/server';
import { useAuth, useJWTQueryParam, useOAuth2 } from './components/idiot/auth/auth.middleware';
import { getRequestedURI } from './components/idiot/auth/utils';
import log from './components/idiot/next-log/log';
export type MiddlewareHook = (req: NextRequest) => Promise<{
activated: boolean;
response: NextResponse;
}>;
export const mergeConfigs = (obj1: any, obj2: any): any =>
Object.keys(obj2).reduce(
(acc, key) => ({
...acc,
[key]:
typeof obj2[key] === 'object' && obj2[key] !== null && obj1[key] ? mergeConfigs(obj1[key], obj2[key]) : obj2[key],
}),
{ ...obj1 },
);
export const useNextAPIBypass: MiddlewareHook = async (req) => {
const toReturn = {
activated: false,
response: NextResponse.next(),
};
if (
req.nextUrl.pathname.startsWith('/_next/') ||
req.nextUrl.pathname.startsWith('/api/') ||
req.nextUrl.pathname === '/favicon.ico'
) {
toReturn.activated = true;
}
return toReturn;
};
export const useSocketIOBypass: MiddlewareHook = async (req) => {
const url = new URL(getRequestedURI(req));
return {
activated: url.host === 'socket.io',
response: NextResponse.next(),
};
};
export const useDocsPublicAccess: MiddlewareHook = async (req) => {
if (req.nextUrl.pathname === '/docs') {
return {
activated: true,
response: NextResponse.redirect(new URL('/docs/0-Introduction', req.url)),
};
}
return {
activated: req.nextUrl.pathname.startsWith('/docs'),
response: NextResponse.next(),
};
};
export default async function Middleware(req: NextRequest): Promise<NextResponse> {
log([`MIDDLEWARE INVOKED AT ${req.nextUrl.pathname}`], {
server: 1,
});
const hooks = [useNextAPIBypass, useDocsPublicAccess, useOAuth2, useJWTQueryParam, useAuth];
for (const hook of hooks) {
const hookResult = await hook(req);
if (hookResult.activated) {
hookResult.response.headers.set('x-next-pathname', req.nextUrl.pathname);
return hookResult.response;
}
}
return NextResponse.next({
headers: {
'x-next-pathname': req.nextUrl.pathname,
},
});
}