Troubleshooting a NextJS Middleware Issue: Retrieving a Blank Screen After Token Verification

I'm currently developing a Spotify Clone using its API and utilizing Next JS Middleware to enforce redirect conditions. The purpose of these conditions is to verify if the user has a token; if not, they should be redirected to the login page.

For some unknown reason, I'm encountering a blank white screen while running the application.

Below is the content of the middleware.ts file

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

export async function middleware(request: NextRequest) {
    const token = await getToken({ req: request, secret: process.env.JWT_SECRET });

    const { pathname } = request.nextUrl;

    if (pathname.includes("/api/auth") || token) {
        return NextResponse.next();
    }

    if (!token && pathname !== '/login') {
        return NextResponse.rewrite(new URL('/login', request.url));
    }
}

The directory structure looks like this

https://i.sstatic.net/HLdr6.png

If you can offer any assistance, it would be greatly appreciated. You can find the full code here https://github.com/dipesh2508/Vibes

Answer №1

After examining your middleware, it appears that you are currently blocking all JS resources, including the essential _next folder needed to load the application itself.

To resolve this issue, you will need to adjust your conditions accordingly. As a starting point, you can consider the following code snippet:

if (!token && pathname !== '/login' && !pathname.includes("/_next/")) {
  return NextResponse.rewrite(new URL('/login', request.url));
}

Keep in mind that you may also need to exclude your public assets from being blocked, such as favicon.ico.

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

Is there a way to navigate to a specific component selector within an ngFor loop?

I have a scenario where I have multiple components running inside *ngFor on the same page. My goal is to create button links at the top of the page that, when clicked, will scroll to the corresponding component on the page. Below are the code snippets tha ...

The Enigmatic Essence of TypeScript

I recently conducted a test using the TypeScript code below. When I ran console.log(this.userList);, the output remained the same both times. Is there something incorrect in my code? import { Component } from '@angular/core'; @Component({ sel ...

Is it recommended to create a static page in NextJS for a blog post that includes comments

Hey there! So, I've got this blog page where all the posts are saved in a database. Users can suggest changes to posts and leave comments as well. The URL path for the post is /app/posts/[name]/page.tsx. Do you think it's a good idea to use stati ...

Creating a JavaScript library with TypeScript and Laravel Mix in Laravel

I have a Typescript function that I've developed and would like to package it as a library. To transpile the .ts files into .js files, I am using Laravel Mix and babel ts loader. However, despite finding the file, I am unable to use the functions: ...

Is it necessary for the React generic type prop to be an extension of another type

I have recently started using TypeScript and I am facing a confusion regarding passing generic types into my higher-order component (HOC). My objective is to pass the component props as a generic type in order to have the Component with those specific type ...

The ES6 import feature conceals the TypeScript definition file

I currently have two definition files, foo.d.ts and bar.d.ts. // foo.d.ts interface IBaseInterface { // included stuff } // bar.d.ts interface IDerivedInterface extends IBaseInterface { // more additional stuff } Initially, everything was funct ...

Optimal Approach for Integrating Vimeo Videos in Next.js or React.js

Currently building a website using Next.js and looking for the best way to embed Vimeo videos. I have experimented with regular iframes, react-player, and @u-wave/react-vimeo. However, I have encountered some issues such as getting a 410 error with @u-wav ...

TypeScript versions 2.3 and 2.4 experiencing issues with generic overloads

After upgrading from typescript 2.2, I encountered an issue with the following example. interface ILayoutResult { id: string; data: any; } interface ILayout{ getResult<T extends ILayoutResult | ILayoutResult[] | void>() :T; } class te ...

What is the proper way to import the Database class from BetterSqlite3 in a TypeScript project?

I am currently working on code that utilizes better-sqlite3 and my goal is to convert it to typescript. The original javascript code includes the following relevant sections: import Database from "better-sqlite3"; /** * @param {string} filenam ...

What is the best way to integrate a Next.js Image component with a set width and an adaptable height in order to maintain the image's proportions?

This code snippet uses ChakraUI styling and retrieves images from SanityCMS: <Box w="500px" h="500px" bg="red"> <Image src={allArtPieces[0].imageUrl} alt={allArtPieces[0].title} width="500px" ...

Using RXJS with Typescript to wait for an observable to emit until another observable of type boolean evaluates to false

In my current setup, when a user navigates in a view, an API call is made to fetch the data for that specific view. This data is then used later on to decide whether a dialog should pop up when a user performs an action. While the solution is functional a ...

What is the best way to display the complete text or wrap a menu item in an Angular Material menu?

Is it possible to display the full text of a menu item instead of automatically converting it to ellipses or breaking the word? I've tried various CSS methods without success. Any suggestions? https://i.stack.imgur.com/3l7gE.png #html code <mat-m ...

In need of guidance to troubleshoot the error "Encountering problem while reading properties of undefined (jwt)"

I'm currently facing an authentication flow issue and I am looking for assistance from someone with a keen eye to help me troubleshoot and resolve the problem. The specific error message I am encountering is [next-auth][error][JWT_SESSION_ERROR] http ...

What is the solution to the error 'getUserByAccount is not defined' in next-auth?

After updating Next.js to the latest version and also upgrading next-auth and the prisma adapter following the documentation, I encountered an error when attempting to authenticate with the signIn function: [next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR] ...

There has been an error of type TypeError, as the property 'replace' cannot be read from a null value

I encountered a TypeError message, even though my application seems to be functioning properly. "ERROR TypeError: Cannot read property 'replace' of null" I'm struggling to understand how to fix this issue. Can someone provide me ...

Is it necessary to separate Lodash orderby functions to ensure they function correctly?

For some reason, I'm having trouble sorting my data using lodash in my front-end client code. All the examples I've come across don't involve working with data in an interface, so I can't figure out where I'm going wrong. Let&apo ...

Issue: Unable to locate the name 'ContactField' in Ionic 2

While attempting to use Ionic2 to save a contact, an error occurs when running the app through the command line. The cordova-plugin-contacts has been properly installed. Below is the code snippet: import { Component } from '@angular/core'; impo ...

Using Next.js and mongoose to include ObjectId's in an array before saving a new object

For days now, I've been struggling to figure out how to create a new object (Group) that contains selected objectId's (User). The group model is defined as follows: import mongoose from 'mongoose'; const groupSchema = new mongoose.Sche ...

What is the proper way to define the type of an object when passing it as an argument to a function in React using TypeScript?

I'm struggling to figure out the appropriate type definition for an Object when passing it as an argument to a function in React Typescript. I tried setting the parameter type to "any" in the function, but I want to avoid using "any" whenever passing ...

Utilizing Typescript to implement an interface's properties

After declaring an interface as shown below interface Base { required: string; } I proceeded to implement the interface in a class like this class MyClass implements Base{ method(): void { console.log(this.required); } } However, I ...