title: Next auth v4 with Next.js middleware
body: <p>I'm using Next.js with next auth v4 for authentication with credentials.</p>
  <p>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.</p>
  <p>I wanna also add protected route and unprotected routes for login page and other pages that is not necessary to check authentication on it.</p>
  <p>Here is my code:
  <code>[...nextauth].js</code></p>
  <pre><code>import NextAuth from &quot;next-auth&quot;
  import CredentialsProvider from &quot;next-auth/providers/credentials&quot;;
  import api from './api'
  
  export default NextAuth({
      providers: [
          CredentialsProvider({
            name: &quot;Credentials&quot;,
            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 &gt; 0
              if (account &amp;&amp; success) {
                  return {
                  ...token,
                  user : user ,
                  accessToken: user.id            
                };
              }
              return token;
          },
      
          async session({ session, token }) {   
            session.user = token;  
            return session;
          },
        },
      secret: &quot;test&quot;,
      jwt: {
          secret: &quot;test&quot;,
          encryption: true,
      }, 
      pages: {
          signIn: &quot;/Login&quot;,
      },
  })
  </code></pre>
  <p>My <code>_middleware.js</code></p>
  <pre><code>import { getSession } from &quot;next-auth/react&quot;
  import { NextResponse } from &quot;next/server&quot;
  
  /** @param {import(&quot;next/server&quot;).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(&quot;/Login&quot;)) {
      return NextResponse.next()
    }
  
    const session = await getSession({req})
    // You could also check for any property on the session object,
    // like role === &quot;admin&quot; or name === &quot;John Doe&quot;, etc.
    if (!session) return NextResponse.redirect(&quot;/Login&quot;)
  
    // If user is authenticated, continue.
    return NextResponse.next()
  }
  </code></pre>