When it comes to deploying middleware, accessing cookies becomes more challenging. However, in a local setup, Next.js allows middleware to

I have set up a NextJS frontend application with a backend powered by NodeJS and ExpressJS. Authentication and authorization are handled using JWT token-based system, where the backend server sets the token and the frontend server validates it to grant access to private routes. Everything runs smoothly locally, but after deployment, I encountered an issue wherein cookies are not being sent from the frontend to access private routes. The middleware in NextJS cannot seem to access the cookies.

Implementation in middleware.js in NextJS:

import { NextResponse } from 'next/server';
import react from 'react';

const middleware = (req) => {

    let verify = req.cookies.get("jwt")
    let url = req.url
    if (!verify && url.includes("/dashboard")) {
       
        return NextResponse.redirect(`${process.env.NEXT_URL}/login`);
    }

};
export default middleware;

Configuration for CORS in index.js of Express application:

if(process.env.NODE_ENV==="Production"){
  corsOptions = {
    credentials: true, origin:process.env.ORIGIN_URL 
  };
}else{
  corsOptions = {
    credentials: true, origin:true
  };
}

app.use(cors(corsOptions))

ProtectMiddleware function in Express JS:

const protect = asyncHandler(async (req, res, next) => {
  let token;
  token=req.cookies?.jwt
  console.log(token)
  if (token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      console.log(decoded)
      req.user = await prisma.user.findFirst({
        where: {
          email: decoded.email,
        },

      });
      next();
    } catch (err) {
      res.status(401);
      throw new Error(`Not Authorized, Invalid Token`);
    }
  } else {
    res.status(401);
    throw new Error(`Not Authorized, No Token`);
  }
});

Note: The NextJS frontend and the backend are on different domains and both are running over HTTPS. I need help resolving the cookie access issue in the middleware after deployment. Any solutions would be greatly appreciated. Thank you.

Answer №1

Have you attempted to access cookies by using the cookies function within the next/headers module?

import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';

const middleware = (req) => {
   const cookieStore = cookies();
   const verify = cookieStore.get('jwt');

   // Your additional code goes here
};

export default middleware;

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

NgModel in Angular Datapicker does not successfully transmit value

My page features a form that functions as a filter search, with one of the fields being a date field. I have configured the Angular UI datepicker plugin (https://github.com/angular-ui/ui-date) and the calendar pops up when I focus on the date field. Howe ...

How can we minimize the data contained in JSON HTML markup?

https://i.stack.imgur.com/mzuB0.png Currently, I am attempting to find a way to conceal the last 12 digits in the price shown on a button, as it is excessively long. The method I am utilizing involves a JSON api and insertAdjacentHTML markup. This snipp ...

Having difficulty configuring HTTPS in Express.js

Currently, I am following a tutorial that seems to be the same as all others I have come across. This is the code I am using: // dependencies var express = require('express') , https = require('https') , fs = require('fs&apos ...

leveraging AJAX to showcase information retrieved from a MySQL database

Hello! I am brand new to PHP and have little knowledge of AJAX. I am in the process of creating a photo gallery site and have used the following code to display my photos. I would like to make it possible, using AJAX or any other language, for someone to c ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...

Leveraging various techniques within a single controller in AngularJS

I am seeking assistance and advice on a coding issue I am facing. I am attempting to use two methods in one controller. The first method is to display selected rooms, while the second method is to display selected pax. However, only the first method seems ...

An npm list is always full of modules

As I prepare to install a package using npm, I noticed that my folder for the new project already has numerous items listed when I run npm list. Is it normal for the folder not to be empty at this stage? Have I made an error somewhere? ...

Creating a dynamic JSON array with a single key as an array

After converting data from an excel sheet into a json array, here is the structure: [{ 'booktitle': 'Leading', 'bookid': '56353', 'bookauthor': 'Sir Alex Ferguson' }, { 'booktitle&ap ...

Concealing objects identified by a specific id

I have two separate div elements var promptContent = $('<div id="errorr">').addClass("formErrorContent").html(promptText).appendTo(prompt); var arrow = $('<div id="errorrarrow">').addClass("formErrorArrow"); I need to refe ...

"Encountering an error with the any type in the useLocation feature while using React Router version 6

https://i.sstatic.net/0YcS9.png What steps should I take to resolve this particular type of error issue? My attempt at passing a custom type did not yield successful results. ...

One effective way to utilize await/async within the Vue mounted lifecycle hook is by

I am facing an issue where the mapGetters value is showing null in my computed property because the preferences method is not executed completely. I need to wait until the store has set the getter and setter. I have tried using async/await but it's no ...

I am encountering an issue where the POST data is not being successfully sent using XMLHttpRequest unless I include

I have a unique website where users can input a cost code, which is then submitted and POSTed to a page called 'process-cost-code.php'. This page performs basic validation checks and saves the information to a database if everything is correct. T ...

Using Jquery to add a list after parsing JSON data stored in localStorage

I've been stuck on this issue for quite some time now. The problem I'm facing involves checking the localStorage to see if there's a cached JSON string available. If there is, I load it and convert it back into a JSON object. If not, I make ...

Commit to persevering until you achieve success

I'm currently working with native node.js Promises and did not find any useful information in this thread. Essentially, I am dealing with a function that looks like this: var foo = foo (resolve, reject) { return obj .doA() .doB() ...

Set the height of a div based on the height of another div

My challenge involves a textarea that dynamically expands as content is added to it. The structure of the textarea within a div element is illustrated below: <div id='sendMes' class='container-fluid'> <form action='#&apos ...

Encountering a Next.js error when attempting to execute code on a live server

Encountering a frustrating error: Failed to compile ./utils/styles.js Error: failed to process internal error: entered unreachable code: assign property in object literal is invalid This annoying error popped up during the build process and can only be res ...

Using the routes API in Next.js, delete files from the client's Public folder

In my application, users have the ability to create QR codes. These generated QR codes are saved as PNG files in the public folder for easy access and downloading. However, I want to ensure that unused QR codes can be deleted by the user without clutteri ...

Tips for automatically scrolling mat-select option to the top when mat-select is closed

Is there a way to automatically scroll the mat-select options to the top after closing it? I am faced with a situation where I have numerous options in my mat-select dropdown. If I select an option from the bottom and then close the mat-select, is there a ...

Angular 12: Running ng test shows code coverage error - TypeError: Unable to access 'initialize' property as undefined

I encountered an error in the code coverage console: TypeError: Cannot read properties of undefined (reading 'initialize') I am trying to call a service method from the component.ts file The code in the component.ts file looks like: this.myAuth ...

When using Promise.all(), it surprisingly gives back an array of Promise <Pending>'s that are undefined, even though other solutions produce successful results

Currently, I am in the process of developing a web application that enables users to access a dashboard displaying various items. Each item comprises sections labeled as a, b, and c, which are represented as complete (o) or incomplete (x) on the dashboard. ...