-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
50 lines (43 loc) · 1.43 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
import { auth0 } from '@/auth0';
import * as Sentry from '@sentry/nextjs';
import { createEdgeRouter } from 'next-connect';
import { type NextFetchEvent, type NextRequest, NextResponse } from 'next/server';
// Middleware
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - monitoring (sentry tunnel)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
'/((?!_next/static|_next/image|monitoring|favicon.ico|sitemap.xml|robots.txt).*)',
]
};
export async function middleware(request: NextRequest, event: NextFetchEvent) {
return router.run(request, event);
}
// Router
const router = createEdgeRouter<NextRequest, NextFetchEvent>();
router
.use(async (request, _, next) => {
const session = await auth0.getSession();
Sentry.setUser({
id: session?.user?.sub,
email: session?.user?.email,
ip_address: request.headers.get('X-Forwarded-For') ?? undefined,
});
return next();
})
.use('/ip/', async (request, _, next) => {
const session = await auth0.getSession();
if (!session) {
return NextResponse.redirect(`${request.nextUrl.origin}/auth/login?returnTo=${encodeURIComponent(request.nextUrl.pathname)}`);
} else {
return next();
}
})
.all(async (request) => {
return await auth0.middleware(request);
});