Middleware in Next.js Only Works for the First Request from Client-Side Navigation

I’m working with Next.js and facing an issue where middleware is not being triggered on subsequent navigations from a client-side route. Specifically, I’m using router.push in a React component with use client, but it seems that the middleware only performs its check on the first request and does not re-evaluate subsequent navigations. (NextJS 14)

Problem :
I have the following middleware configuration :

//app/user/signIn/page.js

'use client'

import { useState } from 'react'
import { signIn } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import Link from 'next/link';

export default function SignIn() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState(null)
  const router = useRouter()

  const handleSubmit = async (e) => {
    e.preventDefault()
    try {
      const result = await signIn('credentials', {
        redirect: false,
        email,
        password,
      })

      if (result.error) {
        setError('email or password is incorrect.')
      } else {
        router.push('/user/profile')
      }
    } catch (error) {
      console.log('error', error)
      setError('An unexpected error occurred. Please try again later.')
    }
  }

  return (
    <>
      <div className='text-center'>
        <Link href="/user/profile" className="block mb-2">[Profile Menu]</Link>
        <Link href="/user/signIn" className="block mb-2">[Login Menu]</Link>
      </div>
      <div className="flex items-center justify-center">
        <form
          onSubmit={handleSubmit}
          className="bg-white p-6 rounded-md shadow-md"
        >
          <div className="mb-4">
            <label htmlFor="email">Email</label>
            <input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              className="w-full border border-gray-300 px-3 py-2 rounded"
            />
          </div>
          <div className="mb-4">
            <label htmlFor="password">Password</label>
            <input
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              className="w-full border border-gray-300 px-3 py-2 rounded"
            />
          </div>
          {error && <p className="text-red-500 mb-4">{error}</p>}
          <button
            type="submit"
            className="w-full bg-blue-500 text-white py-2 rounded mb-4"
          >
            Sign In
          </button>
        </form>
      </div>
    </>
  )
}

//app/user/profile/page.js

'use client'

import { useSession, signOut } from 'next-auth/react'
import Swal from 'sweetalert2'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'

export default function Profile() {
    const { data: session, status } = useSession()
    const [userData, setUserData] = useState(null)
    const router = useRouter()

    useEffect(() => {
        if (status === 'unauthenticated') {
            router.push('/user/signIn')
        }
    }, [status, router])

    useEffect(() => {
        if (session?.user?.id) {
            fetch(`/api/user/${session.user.id}`)
                .then(res => res.json())
                .then(data => setUserData(data))
                .catch(error => {
                    console.error('Error fetching user data:', error)
                    Swal.fire('Error', 'Unable to fetch user data', 'error')
                })
        }
    }, [status, session])

    const handleSignOut = async () => {
        const result = await Swal.fire({
            title: 'Do you want to logout?',
            text: "Confirm logout.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel'
        })

        if (result.isConfirmed) {
            signOut({ callbackUrl: '/user/signIn' })
        }
    }

    return (
        status === 'authenticated' &&
        session.user && (
            <>
                <div className="flex h-screen items-center justify-center">
                    <div className="bg-white p-6 rounded-md shadow-md">
                        <p>
                            Welcome, <b>{userData?.firstName} {userData?.lastName}!</b>
                        </p>
                        <p>Email: {userData?.email}</p>
                        <p>Role: {userData?.role.title}</p>
                        <button
                            onClick={handleSignOut}
                            className="w-full bg-blue-500 text-white py-2 rounded"
                        >
                            Logout
                        </button>
                    </div>
                </div>
            </>
        )
    )
}

//middleware.js

import { getToken } from 'next-auth/jwt';
import { NextResponse } from 'next/server';

export async function middleware(request) {
  const user = await getToken({
    req: request,
    secret: process.env.NEXTAUTH_SECRET,
  });

  if (request.nextUrl.pathname.startsWith('/user/profile') && !user) {
    const signInUrl = new URL('/user/signIn', request.url);
    return NextResponse.redirect(signInUrl);
  }

  return NextResponse.next();
}

//app/api/auth/[…nextauth]/route.js

import NextAuth from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import { PrismaClient } from '@prisma/client'
import bcrypt from 'bcrypt'
import { PrismaAdapter } from '@auth/prisma-adapter'

const prisma = new PrismaClient()

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: 'Credentials',
      credentials: {
        email: { label: 'Email', type: 'email', placeholder: '[email protected]' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials, req) {
        if (!credentials) return null
        const user = await prisma.user.findUnique({
          where: { email: credentials.email },
        })

        if (
          user &&
          (await bcrypt.compare(credentials.password, user.password))
        ) {
          return {
            id: user.id,
            firstName: user.firstName,
            lastName: user.lastName,
            email: user.email,
            roleId: user.roleId
          }
        } else {
          throw new Error('Invalid email or password')
        }
      },
    })
  ],
  adapter: PrismaAdapter(prisma),
  session: {
    strategy: 'jwt',
  },
  callbacks: {
    jwt: async ({ token, user }) => {
      if (user) {
        token.id = user.id
        token.roleId = user.roleId
      }
      return token
    },
    session: async ({ session, token }) => {
      if (session.user) {
        session.user.id = token.id
        session.user.roleId = token.roleId
      }
      return session
    }
  },
}

const handler = NextAuth(authOptions)

export { handler as GET, handler as POST }

Issue:

  • When I navigate to /user/profile after signing in, the middleware performs the redirection as expected if there is no token.
  • However, when I navigate to /user/profile again from the client-side using router.push, the middleware does not re-check or perform the redirection again.

Question:

Is this behavior expected with Next.js middleware? Why does the middleware only trigger on the first request and not on subsequent navigations from the client-side? How can I ensure that the middleware runs and performs checks on every request, even those triggered by router.push from a client-side component?

Additional Information:

  • I’m using Next.js with NextAuth for authentication.
  • My goal is to make sure that every time a user tries to access /user/profile, the middleware checks for a token and redirects to the sign-in page if the token is missing.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật