-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
28 lines (26 loc) · 899 Bytes
/
middleware.js
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 { NextResponse } from 'next/server'
import { isAuthenticated } from '@/lib/auth'
// Limit the middleware to paths starting with `/api/`
export const config = {
matcher: '/api/secure/:function*',
}
export async function middleware(request) {
// Call our authentication function to check the request
const checkAuth = await isAuthenticated(request);
if (!checkAuth.success) {
// Respond with JSON indicating an error message
return new NextResponse(
JSON.stringify({ success: false, message: 'authentication failed', checkAuth: checkAuth }),
{ status: 401, headers: { 'content-type': 'application/json' } }
)
}
const requestHeaders = new Headers(request.headers)
requestHeaders.set('userId', checkAuth.data)
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders
},
})
return response
}