Incorporating middleware in Next.js to remove route protection

Looking to remove the protection for the login page, and here is how my folder structure looks:

https://i.stack.imgur.com/klPYV.png

This is the middleware I am using:

import { NextResponse, NextRequest } from "next/server";

export async function middleware(req, ev) {
  if (req.pathname === "login") {
    return NextResponse.next();
  }
  const token = req.cookies.token;

  if (!token) {
    return NextResponse.redirect("/login");
  }
  return NextResponse.next();
}

Querying on how to exclude login.js from the middleware.

Edit: now getting

[webpack.cache.PackFileCacheStrategy] Caching failed for pack: Error: Unable to snapshot resolve dependencies

The code for this project can be found here

Answer №1

After some troubleshooting, I identified the issue - I wasn't retrieving the pathname from req.nextUrl. Here's the updated and corrected code:

import { NextResponse, NextRequest } from "next/server";

export async function middleware(req, ev) {
  const { pathname } = req.nextUrl;
  const token = req.cookies.token;

  if (pathname == "/login" && !token) {
    return NextResponse.next();
  }

  if (!token) {
    return NextResponse.redirect("/login");
  }

  return NextResponse.next();
}

Answer №2

To ensure that the request is for the "/login" page itself, you can quickly exit the process.

Explore all the available properties on NextRequest.

import { NextResponse, NextRequest } from "next/server";

export async function middleware(req, ev) {
  if( req.pathname === 'login'){
      return NextResponse.next();
  }
  const token = req.cookies.token;

  if (!token) {
    return NextResponse.redirect("/login");
  }
  return NextResponse.next();
}

Answer №3

The solution provided in the accepted answer was incredibly helpful to me. I decided to share my modified version of the solution that worked for my specific case.

In my implementation, I utilized a file named [...nextauth].js with callbacks for jwt and session. However, I encountered an issue where I kept receiving a cycle of ERR_TOO_MANY_REQUESTS errors when using the original solution from the accepted answer. To resolve this, I made adjustments by including a few additional URLs:

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

export default async function middleware(req, ev) {
  const { pathname } = req.nextUrl;
  const token = await getToken({ req, secret: process.env.JWT_SECRET });

  if ((pathname == "/api/auth/signin" || pathname == "/favicon.ico" || pathname == "/api/auth/callback/credentials") && !token) {
    return NextResponse.next();
  }

  if (!token) {
    return NextResponse.rewrite(new URL('/api/auth/signin', req.url));
  }

  return NextResponse.next();
}

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

When utilizing Javascript's Array.push method, a nested array is generated that is inaccessible using the index

I have reviewed several articles discussing the issue of asynchronous calls returning undefined. Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference Get data from fs.readFile However, none of these articles ...

Show the components only if the final digit in their identification number is less than i

I have several span elements with IDs like "tag1", "tag2", etc. I want to display only the spans whose ID ends with a number less than 19. These elements are part of a class called "notVis", which is hidden by default using $(".notVis").hide(); when the ...

How should I proceed if both fields are encrypted by Mongoose Encryption?

const adminsSchema = new mongoose.Schema({ username: String, password: String, }); const secretKey = "CrackThis1"; adminsSchema.plugin(encrypt, { secret: secretKey, encryptedFields: ["password"] }); const AdminUser = ne ...

New replacement for routerState.parent feature that has been deprecated in angular2

During my work with Angular 2 rc5, I encountered the following code snippet. this.router.routerState.parent(this.route).params.forEach((params: Params) => { url = params['url']; id = +params['id']; }); I had to resort to th ...

"Need help passing an API key in the header of a Vue.js project? I recently encountered this issue while using a

How can I include an API key in the header of a Vue.js request? I am using DRF pagination. methods: { getPostData() { axios .get("http://192.168.43.126:8000/api/?page=" + this.currentPage, { headers: { &q ...

You cannot make a hook call within the body of a function component, unless you are using useNavigate and useEffect in conjunction with axios interceptors

Currently, I am delving into React and attempting to include a Bearer token for private API calls. My approach involves writing a private axios function to intercept requests and responses. Subsequently, I invoke it in my API.js file to fetch data from the ...

After the installation of Windows 10 and the latest version of NodeJS, Gatsby seems to be

The gatsby project I set up following the official website instructions seems to be malfunctioning. NodeJS version: v16.15.0, npm version: 8.8.0, gatsby version: 4.13.0, gatsby CLI version: 4.13.0 C:\Users\Dell\Desktop\New folder&bsol ...

Discovering the correct element and typing for an HTML attribute through JavaScript

We are currently working on test automation and I am looking for a way to identify the Element and Type associated with it within an html (Data-qa) attribute. For example, when looping through, the Element is identified as input and the type is radio. < ...

Azure deployment for Angular app was unsuccessful due to npm startup failure

I've been trying to deploy my Angular application on Azure. While I can successfully publish it using Azure, I keep encountering an error message when trying to access the published site: AggregateException: One or more errors occurred. (One or more ...

I am seeking to showcase an image in a window, and upon the image being clicked, execute the code in a separate window

I am looking to showcase the image provided below. <img src="http://gfx.myview.com/MyView/skins/livesample/image/livesample.gif" alt="" border="0"><a/> Once the image is clicked, I want it to execute the following code. How can I ensure that ...

Retrieve the content of the specified element within the webpage

How can I modify the method to successfully retrieve the text content of an element on a webpage using Selenium with JavaScript? Currently, it is returning undefined. homepage.js const { Builder, By, Key, until } = require('selenium-webdriver'); ...

The AWS Beanstalk CLI continues to deploy React and npm development builds

I have a React application along with two AWS Beanstalk instances: one for development and the other for production. My goal is to deploy the development build of the React app to the development environment and the production build to the production envir ...

Stop or abort any pending API requests in Restangular

I am currently working with an API service: var SearchSuggestionApi = function (Restangular) { return { getSuggestion: function (keyword) { return Restangular.one('search').customGET(null, {keyword:keyword}); } }; }; SearchS ...

The paths specified in Node.js and Express are having difficulty finding the resource files for CSS and JavaScript

I am currently using Express to develop a basic website. Everything was running smoothly until I attempted to add the following code to handle 404 errors: app.get('/*', function(req, res) { res.render('404.ejs',{ title: ' ...

Node application running in Docker cannot establish connection with the Postgres database also running in Docker

I've experimented with various solutions, but none of them seem to work for me. Here's what I did: I set up a nodejs container and a postgres docker container. I used docker compose to configure both and a Dockerfile to build the nodejs/typescri ...

Unable to eliminate hover underline on link

Struggling to remove the underline from all links globally in my NextJS project has been quite a challenge. I've attempted various methods, including CSS (by importing the globals.css file into _app.tsx) and through ChakraUI. The only solution that ...

Reasons for Axios converting HTTP requests to HTTPS in ReactJS

Encountering an issue with a get request in my ReactJS app: const response = await axios.get("http://xx.xxx.xx.xx:3002/api/products/allTimers", { headers: { 'Authorization': 'Bearer ' + this.state.authoriza ...

Eliminate Dates from the Past - Jquery Datepicker

Currently, I am developing a booking system for my client. I have successfully disabled Sundays and Mondays (the days she is not open). However, I am now working on enhancing the functionality by blocking out past dates. Although I have written a function ...

Make dark mode the default setting in your Next JS application

In my Next JS application, I have implemented both isDarkMode and handleDarkMode functions. Within the Header component, there is a toggle button that allows users to switch between light and dark modes. <ThemeContainer> <label classN ...

Using Tailwind classes as a prop functions correctly, however, it does not work when directly applied

Here's a component snippet I'm working on: export const TextInput = ({ label, wrapperClassName = "", inputClassName = "", labelClassName = "", placeholder = "", ...props }: InputProps & Fiel ...