Next.JS-13 detects faulty middleware in App routing

Here is the code snippet from the middleware file:

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

// This function can be marked as `async` if using `await` inside
export function middleware(request: NextRequest) {
    const path = request.nextUrl.pathname;
    const isPublicPath = path === '/login' || path === '/signup';
    const token = request.cookies.get('token')?.value || '';
    if (isPublicPath && token) {
        return NextResponse.redirect(new URL('/', request.nextUrl));
    }
    if (!isPublicPath && !token) {
        return NextResponse.redirect(new URL('/login', request.nextUrl));
    }
}

// Check out "Matching Paths" for more information
export const config = {
    matcher: ['/', '/profile', 'login', '/signup'],
};

An error occurred:

source does not start with / for route {"source":"login"}

Error: Invalid middleware detected

Any solutions to this issue?

Answer №1

In the official documentation, it is explicitly stated that matcher paths must (clearly emphasized in uppercase letters) always begin with /:

List of configured matchers:

  1. Should always start with /

Therefore, make sure to remember to include that essential /:

export const config = {
    matcher: ['/','/profile', '/login', '/signup'],
                              ☝️ Just Right Here
};

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

What is the method to retrieve the time elapsed since the document's creation in MongoDB using Node.js

I am requesting to find out the duration since the account was established: console.log('TIMEYWIMEY',req.user.createdAt, new Date(), new Date() - req.user.createdAt) The output is TIMEYWIMEY 2019-05-10T16:12:40.457Z 2019-07-26T16:05:58.142Z NaN ...

Having difficulty converting a list of intricate objects into a CSV format

I am faced with a challenge of handling an array of complex objects, some of which may contain arrays of more objects. My goal is to convert this data into a CSV file. However, whenever there is a list of objects, the information appears as [object Object] ...

Typescript error: Cannot assign type 'undefined' to type 'string | number | symbol'

I need help figuring out how to address a TypeScript error in my code. Here's the scenario: export type status = 'success' | 'error' | undefined; There is an object that maps to different icons based on the status. const iconsMap: ...

Resolve the clash between Jest and Cypress within a React application developed using TypeScript

Encountering a conflict in the React app after installing Cypress with TypeScript. Despite trying to resolve it using GitHub solutions, the issue persists. I am sharing all configuration files in hopes that someone can identify the problem. cypress/tsconfi ...

Validation in Angular2 is activated once a user completes typing

My goal is to validate an email address with the server to check if it is already registered, but I only want this validation to occur on blur and not on every value change. I have the ability to add multiple controls to my form, and here is how I have st ...

Is your Async Waterfall query not getting the push it needs?

Currently, I am utilizing async waterfall to efficiently pass the results of a function to the next one. However, I've encountered an issue when trying to call push on the user resulting from the query. Below is the code snippet: exports.contact ...

Implementing a custom overwrite function in TypeScript's inheritance

Below is a class that I have: export class RestService { private baseUrl: string; constructor(protected http: HttpClient) { this.baseUrl = environment.LOCAL_URL; } public get<T>(resource: string, params?: HttpParams): Observable< ...

Error: The function concat() is not valid for messagesRef.current

I'm currently developing an app that enables users to interact with AI by asking questions related to the uploaded PDF file. However, I've encountered a problem while interacting with AI on the client side - I keep receiving the error 'TypeE ...

Guide on integrating the plyr npm module for creating a video player in Angular2

Looking to implement the Plyr npm package in an Angular 6 application to create a versatile video player capable of streaming m3u8 and Youtube videos. The demos on their npm page are written in plain JavaScript, so I need guidance on how to integrate it in ...

Leveraging both function arguments and the 'this' keyword within a single

I have a JavaScript function that utilizes both the `this` keyword and captures arguments: var Watcher = function() { var callbacks = []; var currentValue = null; this.watch = function (callback) { callbacks.push(callback); if (currentValue ...

Do we need to use the "new" keyword when using ObjectID in a MongoDB query

Recently, I was immersed in a Typescript web project that involved the use of MongoDB and ExpressJS. One particular task required me to utilize a MongoDB query to locate and delete a document using the HTTP DELETE method. However, during the process of exe ...

Guide on setting up multiple Axios instances in NestJS

I'm in the process of migrating an existing Express application to NestJS. Currently, I have a configuration file where I define multiple axios instances for each microservice: export const writeModelApi = axios.create({ baseURL: getWriteModelApiUrl ...

Integrating fresh components into a JSON structure

I've been attempting to insert a new element into my JSON, but I'm struggling to do it correctly. I've tried numerous approaches and am unsure of what might be causing the issue. INITIAL JSON INPUT { "UnitID":"1148", "UNIT":"202B", "Sp ...

Failed to load the Unicode tables required for UTF8Handler in Rails Admin version 1.2.0

I am in the process of upgrading rails 3 to rails 5 and my application is utilizing mongodb as the database. Here are the specifics of my setup - I am using rails admin 1.2.0, jruby-9.1.7.0, and my app is a rails api only application. The gems used in my a ...

Replacing information on Model.insertMany using Mongoose

I am facing a situation where I have code that looks like this: Accounts.insertMany(topAccounts) .then(function (result) { console.log('Succesfully saved '+ result.length + ' documents... closing connection...&a ...

What is the reason for TypeScript resolving this type union as an intersection?

I'm struggling to grasp the logic behind a typescript error that keeps popping up - it feels like there's a fundamental concept swiftly flying over my head, making a "whoosh" sound as it goes by. I stumbled upon this discussion about a similar e ...

Guide to customizing Material UI theme using Typescript in a separate file

Trying to customize Material UI theme overrides can be a bit tricky, as seen in the example below: // theme.ts const theme: Theme = createMuiTheme({ overrides: { MuiButton: { root: { display: 'inline-block', fontWeigh ...

Is it possible for a mongo query that utilizes the $in clause to retrieve results in the exact same sequence as the elements in the $in list?

Currently, I am utilizing the $in clause in a mongodb query. My goal is to have the output ordered exactly as my input list specified in the $in clause. However, the results I am receiving are arranged based on the order of insertion of the objects. From ...

I'm encountering an error while trying to build my Ag-Grid using npm run build, can someone help me figure out

Being relatively new to Next.js and web development in general, my background mainly consists of working with compiled languages. I recently embarked on a project to build a web app using Ag-Grid, drawing inspiration from an example I found on a public Git ...

TS2339: The object does not have a property named 'users'

Transitioning from JavaScript to TypeScript while learning React has presented me with a new challenge. The initial state for my context is blank, which is causing issues with accessing the properties. If you prefer, here is the repository link: https:// ...