Forwarding requests via middleware in next.js 13 AppDir: true

I am currently working on implementing a redirect feature in next.js 13 when the jwt back-end is not received. This is being done with the appdir activated.

This is the code in my middleware.ts file:

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(req: NextRequest) {
  const token = req.cookies.get('token')
  if (!token) {
    return NextResponse.redirect('/login')
  }
  return NextResponse.next()
}

Answer №1

This solution seems promising

return NextResponse.redirect(new URL('/login', req.url))

An absolute URL appears to be required

Avoid executing this middleware when a user accesses the "login" page.

const currentPath = req.nextUrl.pathname

Examine the pathname on the login page, and only call "next" if pathname is not equal to "login". The middleware should exclude the login page since it does not require protection.

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 best way to dynamically insert an object into a field name in react-final-form?

When using the react-final-form component, you can expect the following result: <Field name="answers[0].name" component="input" type="radio" value="0" /> { answers: [ { name: 'value' } ] ...

Unforeseen alterations in value occur in JavaScript when converting to JSON format

Having trouble generating a gantt chart from a JSON string, specifically with parsing the JSON string into a JSON object. I have a variable myString containing a JSON string that looks like this: {"c": [{"v": "496"}, {"v": "Task name 1"}, {"v": "9, "}, { ...

Having trouble with a JavaScript function as a novice coder

Hello, I'm still getting the hang of JavaScript - just a few days into learning it. I can't figure out why this function I'm calling isn't functioning as expected. Here's the content of my HTML page: <!doctype html> <htm ...

Is there a way for me to modify the status code of a Next.js page?

Is it possible to set the status code 503 for specific pages in my Next app? Currently, every page returns a status code of 200, even if they are undefined. How can I change this? Just to clarify, when I refer to the status code, I mean the status of the ...

Differences between React class properties and ES6 class properties

With React 16.2, defining class properties is done differently with the tagLine example shown below: class Header extends React.Component { tagLine = "Super Hero"; render() { .... } } Contrastingly, in ES6 classes, it's not possible to define ...

Executing a script in the browser console automatically upon clicking a link can be achieved using Python

I am interested in executing JavaScript in my browser's DevTools console. Currently, I have managed to open a specific website through it. Is there a way to achieve this using Python? Here is the code I am currently using: url = 'http://some-we ...

Transforming an older React website with react-helmet-async

I am working on a React site that is client-side rendered and I want to use the react-helmet-async module (version 1.0.7). Here's my scenario in the React app: /public/index.js: <head> <title>My title in the index file</title> ...

Toggle Vue transitions on and off with a boolean parameter

Is there a way to dynamically disable a transition animation in Vue based on a boolean value? Currently, the animation is enabled with the following code: <transition name="fadeUp"> <div v-if="elIsVisible"> <p>Foo Bar</p> ...

What is the best way to handle parsing JSON with special characters in JavaScript?

Content stored in my database: "Recommended cutting conditions" When using Json_encode in PHP, the result is: {"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]}; In JavaScript : var str ...

Is it true that Safari restricts AJAX Requests following a form submission?

I've developed a JavaScript-based upload progress meter that utilizes the standard multipart submit method instead of submitting files in an iframe. The process involves sending AJAX requests during submission to retrieve the percentage complete of th ...

Next.js Theme Switch using Material-UI Integration

I am currently working on implementing a theme toggle feature similar to the one on the material-ui website. Take a look at my Github Repo: https://github.com/jonnyg23/flask-rest-ecommerce/tree/next-app-migration After studying the material-ui website, I ...

Having trouble with `Routes.push()` in NextJS?

When attempting to access the app dashboard without authentication, I wanted to redirect the user to the homepage. However, I encountered an issue with Route.push() not working as expected. To test this behavior further, I modified Router.push('/&apo ...

How does React determine if a component is a class component or a functional component?

Within my React application, I have successfully developed both a class component and a functional component. However, I am curious about how React is able to distinguish between the two when calling them. Can you shed some light on this distinction? This ...

Transcribing live content directly from the browser tab

I have a unique idea for developing a browser extension specifically for Chrome. This extension would provide live transcriptions of my team's meetings directly from an open tab in the browser. I am interested in extracting keywords, such as my name, ...

Adding HTML content using jQuery's document.ready feature

As a jQuery novice, I am attempting to incorporate a Facebook like button using the jQuery document.ready function. In my external Javascript file (loaded after the jQuery script), you will find the following code snippet: $(document).ready(function(){ ...

Module fails to load in the proper sequence

As a .NET developer who is relatively new to modern client-side web applications, I am currently working on developing an Angular2 charting application using Chart.js. The modules are being loaded with SystemJS. Below is the content of my systemjs.config. ...

Unable to insert hyperlinks into table rows within a React application

A React function was created by me to display a table. This is how the table appears. It accepts JSON as a parameter: { "id": 1, "firstName": "Richard", "lastName": "Morrison", "number ...

Fetching JSON data using Javascript/JQuery

My goal is to access JSON data from an online web service that queries a MySQL database for a specific string and use Javascript to present it on an HTML page. My challenge lies in effectively displaying the retrieved information. The relevant part of my ...

How to move a div beneath the JavaScript files in Drupal 7

I am facing a challenge where I need to position a div right above the body tag without interfering with the scripts located above it. Despite my efforts, I have not been successful in achieving this goal. I attempted to use Hook_page_build to position t ...

What is the best way to upgrade to a specific version of a child dependency within a module?

npm version: 7.24.2 Looking for assistance on updating a child dependency. The dependency in question is: vue-tel-input This dependency relies on libphonenumber-js with version ^1.9.6 I am aiming to update libphonenumber-js to version ^1.10.12. I have ...