-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmiddleware.ts
More file actions
28 lines (26 loc) · 952 Bytes
/
middleware.ts
File metadata and controls
28 lines (26 loc) · 952 Bytes
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
import { withAuth } from 'next-auth/middleware';
import { NextResponse } from 'next/server';
export default withAuth(
function middleware(req) {
if (req.nextUrl.pathname.startsWith('/api') && req.nextauth.token?.user.role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
if (
req.nextUrl.pathname.startsWith('/admin') &&
req.nextauth.token?.user.role !== 'ADMIN'
) {
return NextResponse.rewrite(new URL('/', req.url));
}
if (req.nextUrl.pathname.startsWith('/user') && !req.nextauth.token?.user.role) {
return NextResponse.rewrite(new URL('/auth/login', req.url));
}
},
{
callbacks: {
authorized: ({ token }) => !!token,
},
},
);
export const config = {
matcher: ['/admin/:path*', '/user/:path*', '/api/category/:path*', '/api/product/:path*'],
};