nextjs 13 app router middleware use session #7
Replies: 2 comments
-
|
Hey @zilkenberg22 You should be able to use the session in the middleware and the page router by passing the request object to it.
// Example for middleware, protecting API routes
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { session } from '../lib/session'; //We import it from the initialisation file we created earlier
// Limit the middleware to paths starting with `/api/`
export const config = {
matcher: '/api/:function*',
}
export function middleware(request: NextRequest) {
// Get data from session
const userId = await session(req).get('user_id');
// CONDITION: If no user id (not logged in) then throw 401 error
if (!userId) {
// Respond with JSON indicating an error message
return Response.json(
{ success: false, message: 'authentication failed' },
{ status: 401 }
)
}
}You can set the condition to whatever you want, it depends on what user data you have stored in the session. I've not tested this package with middleware yet, I've only tested it with App router and Page router, Please let me know if its not working as expected. |
Beta Was this translation helpful? Give feedback.
-
https://nextjs.org/docs/app/building-your-application/routing/middleware#runtime
https://nextjs.org/docs/pages/api-reference/edge#unsupported-apis Therefore, Redis-dependent processing may not be available. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
i want use session in middleware.js protect routes
Beta Was this translation helpful? Give feedback.
All reactions