The issue with NextJs middleware is that it is unable to access the cookie immediately after setting it. A page reload is

Once the cookie is set, I am unable to retrieve it in the middleware without having to refresh the page first. Why does this occur?

The cookie is being set as shown below:

import { getCookies, setCookie, deleteCookie, hasCookie } from 'cookies-next';
import { useRouter } from 'next/router';

export default function LoginPage() {

    const router = useRouter()

    const login = () => {
        if (hasCookie('user')) {
            router.push('/');
            return;
        }

        setCookie('user', 'DHamidi-RandomValue')
        router.push('/');
    }

    return <div className="layout">
        <h2>Login</h2>

        <button onClick={login}>
            Add User Info To Cookie.
        </button>
    </div>
}

I need to access the cookie in the middleware:

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
    if (request.cookies.has('user')) return NextResponse.next()
    
    return NextResponse.redirect(new URL('/login', request.nextUrl.clone()))
}

export const config = {
    matcher: '/admin/:path*',
}

NOTE:

It works perfectly in development mode (npm run dev), but the issue arises in production mode (

npm run build => npm run start
). If you would like to observe the problem firsthand, please clone this simple project.

Answer №1

By setting the cookie with the path=/ parameter, you can easily access it without needing to refresh the page. Feel free to confirm if this method works for you.

Here is an example of how you can set the cookie in your code:

res.setHeader('Set-Cookie', token=${token}; HttpOnly; Max-Age=${60 * 60}; Path=/; SameSite=None; Secure);

Answer №2

It seems like you're facing an issue where your Next.js middleware isn't consistently triggered in production mode as it is in development mode. This could be attributed to Next.js caching responses to enhance performance and prevent unnecessary re-executions.

To ensure that your middleware runs every time in production, you should set the x-middleware-cache header to no-cache in the redirect response:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  if (request.cookies.has('user')) {
    return NextResponse.next(); 
  }

  const redirectResponse = NextResponse.redirect('URL_HERE');
  redirectResponse.headers.set('x-middleware-cache', 'no-cache'); // ! FIX: Disable caching
  return redirectResponse;
}

export const config = {
  matcher: '/admin/:path*'
};

By making this adjustment, Next.js will not cache the redirect response in production, allowing your middleware to execute on each request, similar to what occurs in development mode.

For more information, you can check out this GitHub discussion: https://github.com/vercel/vercel/discussions/8173

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Aligning the title of a table at the center using React material

I have integrated material-table into my react project and am facing an issue with centering the table title. Here is a live example on codesandbox: https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js I specifically want to center the title "A ...

Tried to invoke the default export of the file located at C:UsersTeyllayDesktopss.lvfrontendsrcappapollo.ts on the server, but it is intended for the client-side

Question: I am facing an issue with querying user information when entering a specific user page like website/user/1. However, I keep encountering errors and suspect it might be related to Apollo. Is there a way to resolve this problem? What could I have d ...

Steps for rendering a variable-stored component in React

I'm currently working on a block of code designed to display a badge when a passport is due to expire, but no badge should be displayed otherwise: const displayMonths = (passport_date) => { const months = moment().diff(passport_date, 'mo ...

Tips for resolving the error message "TypeError: Cannot access property 'category' of undefined" while working in a React environment

Hey there, I encountered an issue while trying to destructure in react and can't figure out why the title is appearing as an error message. Below is the code snippet: const {correct_answer, incorrect_answers} = data[0] const arr = [correct_answer, ... ...

Adjust the dimensions of the icon

My current project involves creating a sidebar with icons and associated text to represent each icon. However, I encountered an issue while trying to adjust the size of the icons within the sidebar using the "useStyles()" method. For some reason, the size ...

Guide to refreshing the modal component with updated properties

In my application, I have created a modal component for managing recipes. This modal allows users to save recipes to a list. let modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/> However, I also want to utilize the same m ...

How can Next JS automatically route users based on their IP address?

Currently, I am using express and the following method within app.get('/anyPath') to identify the IP address of the client: var ip = req.headers['x-real-ip'] || req.connection.remoteAddress if (ip.substr(0, 7) == "::ffff:") { ...

Parent-sourced Material Tooltip Text Display

I would like to implement a ToolTip in the following manner: const MyComponent = () => { [open, setOpen] = useState(false); return <div (onClick)={() => {setOpen(!open)}> Click to open tooltip <Tooltip text="some ...

What are some creative ways to reveal a concealed card through animation?

I have a collection of MUI cards where one card remains hidden until the others are expanded. My goal is to add animation to the hidden card so it doesn't abruptly appear. Below is the styling and logic for achieving this: ** Styling ** const useStyl ...

Troubleshooting npm authorization problems

I've been experiencing permission challenges while attempting to install certain packages. For instance, I tried installing now-serve using the command npm install -g now-serve and encountered an EACCESS error as follows: npm WARN deprecated <a hr ...

Leveraging split and map functions within JSX code

const array = ['name', 'contact number'] const Application = () => ( <div style={styles}> Unable to display Add name & contact, encountering issues with splitting the array). </div> ); I'm facing difficul ...

Utilize MUI styles on elements that are not originally styled by MUI

I am working on a Gatsby application that utilizes MUI v5 and allows users to input custom markup. I want the user-entered markup to have the same base styles as the corresponding Typography elements (as shown below). How can I make this happen? It is wor ...

What is the best way to implement a sidebar closing animation?

Utilizing both react and tailwindcss, I successfully crafted a sidebar menu that elegantly appears from left to right when the user clicks on the hamburger icon. However, my attempts to create a reverse animation as the sidebar disappears from right to lef ...

What is the best way to display a <div> depending on the screen size in React JS using a global variable, without utilizing state management?

I am attempting to display a message based on the screen resolution in ReactJS. I am utilizing a function component and trying to accomplish this without using state, by using a global variable. const isDesktop = window.innerWidth; {isDesktop > 768 ? ...

Italian calendar conversion for the react-multi-date-picker library

I recently integrated the react-multi-date-picker into my project, utilizing the multiple mode feature. However, I encountered an issue when trying to display the Italian calendar based on the language setting. Despite using locale="it", the calendar was n ...

The element type provided is incorrect: it should be a string or a class/function, but an object was given instead

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. I'm currently working on an application using React JS with Spring Boot. I have successfully configured webpack, but ...

Using react-confetti to create numerous confetti effects simultaneously on a single webpage

I'm looking to showcase multiple confetti effects using the react-confetti library on a single page. However, every attempt to do so in my component seems to only display the confetti effect on the last element, rather than all of them. The canvas fo ...

the <MapView/> component in react-native-maps cannot be displayed

I am attempting to display a native map using the coordinates from the example but encountering an error: *note using iOS and a real device for debugging ERROR: Could not inset compass from edges 9 Could not inset scale from edge Could not inset legal ...

next-redux-wrapper is being invoked repeatedly and experiencing multiple calls to HYDRATE

I'm embarking on a new Next.js project, transitioning from a standard React app to a Next.js application. Our plan is to utilize Redux Toolkit for global state management and incorporate server-side rendering. During this process, we discovered the ne ...

I'm experiencing issues with Tailwind CSS not functioning properly once it's been

I've integrated Tailwind into my Next.js app, and it's functioning as expected on my local machine. However, when I deploy the app to Vercel or build and run it, the Tailwind classes seem to not be applied, giving the impression that Tailwind is ...