-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
52 lines (41 loc) · 1.16 KB
/
middleware.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
49
50
51
52
import micromatch from 'micromatch';
import { getToken } from 'next-auth/jwt';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// Add routes that don't require authentication
const unAuthenticatedRoutes = [
'/',
'/api/auth/**',
'/api/oauth/**',
'/api/scim/v2.0/**',
'/auth/**',
'/login',
'/signup',
'/static/**',
'/_next/**',
'favicon.ico'
];
export default async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// Bypass routes that don't require authentication
if (micromatch.isMatch(pathname, unAuthenticatedRoutes)) {
return NextResponse.next();
}
const token = await getToken({
req,
});
// No token, redirect to login page
if (!token) {
const url = new URL('/login', req.url);
url.searchParams.set('callbackUrl ', encodeURI(req.url))
return NextResponse.redirect(new URL('/login', req.url));
}
const requestHeaders = new Headers(req.headers)
requestHeaders.set('user', JSON.stringify(token))
// All good, next and add user to header
return NextResponse.next({
request: {
headers: requestHeaders,
},
});
}