Reputation: 412
I have created a session using nextAuth and next js 4.23.1, and it works, however I dont know hoy to get the session or token in my middleware, I have tried to pass the handler to the getSession() and doest work at all.
I can get the session in any use clinte component by useSession
How could I get the session and/or token in server side, thanks for your help
in api/auth/[..nextauth]/route
import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import { _AUTH } from "@/app/services/shared/endpoints";
export const handler = NextAuth({
session: {
strategy: 'jwt'
},
providers: [
CredentialsProvider({
async authorize(credentials, req){
const res = await fetch(_AUTH._AUTH_LOGIN, {
method: 'POST',
body: JSON.stringify({user:{...credentials}}),
headers: { "Content-Type": "application/json" }
})
const user = await res.json()
if (!user) {
return
} else {
return user
}
}
})
],
pages: {
signIn: '/login',
}
})
export { handler as GET, handler as POST }
middleware
import { handler } from "./app/api/auth/[...nextauth]/route"
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { getSession } from "next-auth/react"
export async function middleware(request: NextRequest) {
const session = await getSession(handler)
if(session !== undefined || session !== null){
return NextResponse.redirect(new URL('/empresa/mis-empresas', request.url))
}
}
export const config = {
matcher: [
'/empresa/mis-empresas',
]
}
Upvotes: 8
Views: 12766
Reputation: 647
You cannot use getSession
in next.js middleware as getSession works client side only.
You can make use of getToken
which returns the users JWT token and can authenticate with it instead of using session.
For eg:
import { NextResponse, NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
export async function middleware(request: NextRequest) {
// Check for session token
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
});
// Redirect to login page if there's no token
if (!token) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
//add your routes here
],
};
NOTE: For this to work your strategy has to be set to jwt in the next auth options.
Upvotes: 2