Struggling to make fetch function properly within a NextJs middleware function

I am having trouble with redirecting a user to /login if the authentication token from Laravel is invalid. I am attempting to retrieve the user and, if resp.ok() returns false, delete the invalid "token" cookie and direct the user to /login. However, I continue to encounter errors in my browser.

The issue seems to be related to the third if-statement in the code snippet below.

Error: The page isn’t redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete. This problem can sometimes be caused by disabling or refusing to accept cookies.

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

export async function middleware(req: NextRequest) {
  // Add protected routes here
  const url = req.nextUrl.clone();

  if (req.nextUrl.pathname === "/login" && req.cookies.has("token")) {
    url.pathname = "/";
    return NextResponse.redirect(url);
  }

  if (
    !req.cookies.has("token") &&
    req.nextUrl.pathname !== "/login" &&
    !req.nextUrl.pathname.startsWith("/_next")
  ) {
    url.pathname = "/login";
    return NextResponse.redirect(url);
  }
  
  if (req.cookies.has("token")) {
    const user = await fetch(`http://10.129.23.206:8080/api/user`, {
      headers: {
        "Authorization": `Bearer ${req.cookies.get("token")}`,
      }
    })
    
    console.log(user)

    if (!user.ok){
      req.cookies.delete("token")
      url.pathname = "/login";
      return NextResponse.redirect(url)
    }
  }
}

export const config = {
  matcher: ["/", "/create", "/search", "/:slug*", "/login"],
};

Answer №1

It seems that the process of retrieving user information is failing, leading to issues within the conditional statement below:

if (!user.ok){
      req.cookies.delete("token")
      url.pathname = "/login";
      return NextResponse.redirect(url)
    }

In this block of code, the token is deleted, causing a redirection to the "login" page if another request is made without a token:

if (
    !req.cookies.has("token") &&
    req.nextUrl.pathname !== "/login" &&
    !req.nextUrl.pathname.startsWith("/_next")
  ) {
    url.pathname = "/login";
    return NextResponse.redirect(url);
  }

To address this issue, consider wrapping the fetching user code in a try/catch block. In the catch block, handle the error appropriately by potentially displaying an error message on the form instead of triggering a redirection.

Answer №2

Incorporating this approach into my NextJS middleware has been quite effective.

export async function middleware(request: NextRequest){
    (...)
    await fetch("http://localhost:3000/api/foo", {method: "POST", body: JSON.stringify(data)});
    (...)
}

Given that NextJS middleware (the Edge Runtime) lacks support for Node.js APIs and global variables, it appears more suitable to handle certain NodeJS operations within the API router.

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

The getStaticProps function in Next.js does not pass any data back to the pages

After setting up my hosted database, I encountered an issue with fetching data from it. Despite confirming that the database is running smoothly through the Swagger app, no data appears when called via API form. import React from 'react'; export ...

When validation fails, all fields are highlighted in the Div containing the FormGroup

In my Angular application, I need to utilize two fields - produced date and expiry date. It is important to note that I must use <div [formGroup]...> since this component will be called within other forms. Using the form tag here is not an option. ...

What is the best way to interact with and modify the relationships of "many-to-many" fields in my database table?

As someone who is new to nestjs, I am working with two entities: @Entity({ name: "Books" }) @ObjectType() export class Book { @PrimaryGeneratedColumn() @Field() id: number; @Column() @Field() title: string; @ManyToMany(() => Auth ...

The infinite scroll feature is not functioning properly with the combination of get static props and GraphQL

I've been working on a project involving pokeapi graphql, and I developed an infinite scroll component that dynamically loads more pokemon as you scroll down the page. My goal was to preload the first 48 pokemons using static generation. Here's ...

Encountering Router null reference problems during JEST tests due to NextJS v12.2.0

Issues Encountered My upgrade from NextJS v12.1.6 to v12.2.2 went smoothly except for one test file that is causing problems. During the execution of the BreadcrumbTrail test suite, a particular test is failing related to routing. The error suggests a nu ...

Exploring the integration of React.Components with apollo-client and TypeScript

I am in the process of creating a basic React component using apollo-client alongside TypeScript. This particular component is responsible for fetching a list of articles and displaying them. Here's the code: import * as React from 'react' ...

Problem with Angular 5: Data Binding Issue未知EncodingException

Struggling to understand... I want to make a GET request to my service to retrieve the specific hardware associated with the barcode I scanned - this part is working correctly. The hardware information is returned as an object that looks like this -> ...

Encounter the error message "400 Bad Request" while using the Next.js Image

I am currently working on implementing Next.js Image to display an image in my navbar. Below is the code I have written: import Link from 'next/link' import Image from 'next/image' import { Text, useColorModeValue } from '@chakra- ...

Solving the issue of refreshing HTML Canvas drawings in Vue3 using the Composition API

In my typescript code base, I have successfully created a Sudoku board by directly manipulating the DOM and utilizing an HTML Canvas element with its API. Now, I am looking to elevate my project to a full website and integrate what I have into a Vue3 proj ...

Guide on inputting information into a dual-column table where one column is linked to the other

After successfully inserting data with hardcoded values to verify the relation between the 2 columns, I am now wondering if there is a way to reference the value of id in reply_id. This is how I manually inserted data: const { data, error } = await su ...

Ways to retrieve a Class Level Variable within the onCellValueChanged function in agGrid

Exploring Angular with Typescript for the first time. I'm trying to access Class Level Variables within the onCellValueChanged event of agGrid, but encountering the following error: Cannot read property 'updateDict' of undefined Here&apo ...

Utilizing Typescript with Vue 3's Injection Feature

Using the new Vue 3 Composition API, I have created a "store" for reactive data. const state = reactive<State>({ accessToken: undefined, user: undefined, }); export default { state: readonly(state), } When my app is created, I pass the store ...

Utilizing MUI and Next.js 13, we can take advantage of MenuItem and NextLink to manipulate padding and height in order to ensure that the anchor element matches the

The "HTML":  <MenuItem> <NextLink className={currentRoute == "/") ? "link--is-active" : ""} href={"/"}> HOME </NextLink> </MenuItem> When clicking outside the anchor in the nav link, you get a nice MUI effect, but the URL ...

Typescript error in RxJS: Incorrect argument type used

I came across this code snippet from an example in rxjs: Observable.fromEvent(this.getNativeElement(this.right), 'click') .map(event => 10) .startWith({x: 400, y: 400}) .scan((acc, curr) => Object.assign({}, acc, {x: acc ...

Strategies for setting up the runtime dynamically for Nextjs API routes

After deploying my Next.js 13 app on Cloudflare Pages, I encountered an issue with the API routes. To address this, I had to export the runtime variable from each route in the following manner. export const runtime = "edge" During local developm ...

What makes TypeScript believe that the variable could possibly be undefined when it is clearly not the case?

I recently encountered an issue where TypeScript incorrectly identifies a variable as possibly being undefined. Here is a simplified example: const func = (val1?: boolean, val2?: boolean) => { if (!val1 && !val2) return; let result: boolean; ...

Files are nowhere to be found when setting up an angular project

After creating an Angular project, I noticed that some key files were missing in the initial setup, such as app.modules.ts and app-routing.modules.ts The project was generated using the command ng new name Here is a screenshot displaying all the files th ...

Tips for receiving string body parameters from Express routes in TypeScript instead of using the 'any' type?

I have a situation where I am passing a unique identifier called productId as a hidden input within a form: <form action="/cart" method="POST"> <button class="btn" type="submit">Add to Cart</button ...

What could be causing variations in the performance of my Speech Recognition code each time I run it?

Check out my code snippet: export class voiceRecognition { constructor() { } public startVoiceRecognition() { const recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimresults = false; recogn ...

Using TypeScript to consolidate numerous interfaces into a single interface

I am seeking to streamline multiple interfaces into one cohesive interface called Member: interface Person { name?: { firstName?: string; lastName?: string; }; age: number; birthdate?: Date; } interface User { username: string; emai ...