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

Struggling to effectively use XPath to target LI elements that contain specific text

Below is the HTML code for the list item in question: <li class="disabled-result" data-option-array-index="1" style="">4" (0)</li> Here is my attempt at using JavaScript to hide this list item, but it's not working as expected: var xpat ...

Running a Chrome content script once an AJAX request has been triggered by the <body> element

I am facing a challenge with running the content script before the DOM is fully loaded. To give context, there is an AJAX request within a tag which gets triggered on $(document).ready(). Once this request is completed, my extension code kicks in. To tra ...

What is the best approach for dynamically accessing or rendering Children within an Angular Component?

I am facing an issue with reusing a component called wrapper with different child components. I found some helpful resources such as this SO question and this article. However, these only address cases where the child component is known in advance. In my s ...

The React Callservice script is failing to fetch the required data from the Node.js script responsible for making the API call

Recently, I decided to create a basic webpage using React.js to display data fetched from an API. Although the project is intended to be straightforward, my lack of recent development experience has led to a perplexing issue that I can't seem to resol ...

Eliminate Quotation Marks and Commas in String Data Using React

I created a code snippet to input data into a table and added a button function for downloading the entire table. However, when I open the downloaded file using notes or a text editor, it shows multiple double quotes and commas that I need to eliminate. He ...

Create a named export for each specific HTTP method error that occurs when submitting a form to the API

My app is successfully connected to a postgres database using prisma, with the seed.ts file set up and data being sent to the database. However, I'm facing an issue when trying to create an API endpoint using route.js in my api folder. The problem ar ...

Reset an Angular service's public variable

I recently started working with Angular and encountered an issue that I couldn't find a solution for on Google or Stack Overflow. I believe my problem lies in not knowing what to search for. Here is the code snippet causing trouble: JSFiddle HTML &l ...

Struggling to transfer information between components in Next.js version 14

When I try to pass data from one component to another using query, I encounter an issue where the data is undefined or { params: {}, searchParams: {} }. However, in the ProductData component, the data is received correctly. Can you help me identify what I ...

Refreshing a web page in Internet Explorer can cause the HTTP Header content to be altered

As I monitor my dashboard retrieving continuous data from an SAP server, I stumbled upon a solution to fetch the current server date. This approach allows me to display when the dashboard was last updated, and this date is displayed in the DOM. //Method f ...

unable to update the table due to issues with the knockout observableArray

My goal is to collect values from form fields and store them as an object in an observableArray. I want to display these objects in a table so that every time I hit the 'add' button, the table should be updated. However, I am facing issues with t ...

Is there a way to input the Sno data into the database in ascending order?

function table_insert(lease_ids){ var lease_id=lease_ids+1; var table = document.getElementById('table_data123'), rows = table.getElementsByTagName('tr'), i, j, cells, customerId; for (i = 0, j = rows.le ...

JavaScript and AJAX are showing an error message that says: "ReferenceError: x is not

I am currently working on a jQuery function that retrieves the value from a PHP-generated checkbox and sends it through AJAX. The value being sent is always a single word consisting only of letters. Here is the script I have written: <script type="text ...

Can you explain the role of the %GetOptimizationStatus function within a JavaScript file executing in Node.js?

Currently, I am delving into an article that discusses optimization strategies and includes the following code snippet: //Function that contains the pattern to be inspected (using an `eval` statement) function exampleFunction() { return 3; eval(&a ...

Step-by-step guide on uploading an image file using Nextjs

I am attempting to achieve the following: Upload an image file to a Next.js application Process it using cjwbw/real-esrgan:d0ee3d708c9b911f122a4ad90046c5d26a0293b99476d697f6bb7f2e251ce2d4 Retrieve the enhanced version of the image Is there anyone who can ...

Attempting to transfer user information to MongoDB using AngularJS and Node.js

Greetings everyone! I am currently working on a template and trying to develop a backend for it, starting with the registration form. Despite having some kind of connection between my mongodb and my app, data is not being sent to the database. Here is the ...

React State RefreshIs this rewrite good enough?

Displayed above is an image of an object containing two UI controls stored as this.state.controls. Initially, the state values are set with data received before componentDidMount. Updates to the controls' state values are triggered by an event, which ...

Troubleshooting a jQuery filter function selector issue

Here's a function I've created: $.fn.filterByClass = function(cls) { var o = $(this); return o.filter(function() { if ($(this).attr("class") == cls) { return $(this); } }); }; Let's say we have multiple fo ...

The native javascript modal fails to appear

I'm attempting to implement the functionality from this Codepen demo into my project. I've copied over the HTML, CSS, and JavaScript code: <!DOCTYPE HTML> <html> <head> <script> var dialog = docume ...

Display more/hide less form using div elements in a NextJS project

Looking to create a hidden block of amenities on my hotel website that can be expanded and collapsed with buttons in NextJS using tailwind-css. How can I achieve this functionality? Example 1: https://i.stack.imgur.com/BbrUj.png Example-2: https://i.stac ...

Incorporating inputs into express middleware within routes

Currently, I am in the process of constructing a node.js + express RESTful server and looking to streamline the authorization of specific actions through middleware. My objective is to pass parameters to my authorization middleware functions. I'm con ...