I'm using Next.js with next auth v4 for authentication with credentials.
What I want to do is add a global verification for my API calls in a middleware to test before API calls the session. If the session is not null the call have to passed successfully, else if the session is null then handle an unauthorized error message and redirect to login page.
I wanna also add protected route and unprotected routes for login page and other pages that is not necessary to check authentication on it.
Here is my code:
[...nextauth].js
import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
import api from './api'
export default NextAuth({
providers: [
CredentialsProvider({
name: "Credentials",
async authorize(credentials, req) {
const {username,password} = credentials
const user = await api.auth({
username,
password,
})
if (user) {
return user
} else {
return null
}
}
})
],
callbacks: {
async jwt({ token, user, account }) {
let success = user?.id > 0
if (account && success) {
return {
...token,
user : user ,
accessToken: user.id
};
}
return token;
},
async session({ session, token }) {
session.user = token;
return session;
},
},
secret: "test",
jwt: {
secret: "test",
encryption: true,
},
pages: {
signIn: "/Login",
},
})
My _middleware.js
import { getSession } from "next-auth/react"
import { NextResponse } from "next/server"
/** @param {import("next/server").NextRequest} req */
export async function middleware(req) {
// return early if url isn't supposed to be protected
// Doesn't work here
if (req.url.includes("/Login")) {
return NextResponse.next()
}
const session = await getSession({req})
// You could also check for any property on the session object,
// like role === "admin" or name === "John Doe", etc.
if (!session) return NextResponse.redirect("/Login")
// If user is authenticated, continue.
return NextResponse.next()
}