Getting a session in Next.js middleware can sometimes lead to errors during deployment. Here's a guide on how


import type { NextFetchEvent, NextRequest } from "next/server";
import { getSession } from "next-auth/react";
import { NextResponse } from "next/server";

export async function middleware(req: NextRequest, ev: NextFetchEvent) {
  const requestForNextAuth = {
    headers: {
      cookie: req.headers.get("cookie"),
    },
  };
  
  //@ts-ignore
  const session = await getSession({ req: requestForNextAuth });

  if (
    req.nextUrl.pathname.startsWith("/fictions/create") &&
    (!req.cookies.get("~~session") || !session)
  ) {
    return NextResponse.rewrite(new URL("/enter", req.url));
  }

  if (
    req.nextUrl.pathname.includes("/edit") &&
    (!req.cookies.get("~~session") || !session)
  ) {
    return NextResponse.rewrite(new URL("/enter", req.url));
  }

  if (req.nextUrl.pathname.startsWith("/profile") && !session) {
    if (!session) {
      return NextResponse.rewrite(new URL("/enter", req.url));
    }
  }
}

Error Message:  "Dynamic Code Evaluation (e.g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation"

Although it worked fine locally, I encountered errors when deploying the project. It seems like I may have made a mistake somewhere. I want unauthorized users to be redirected to the '/enter' page using next-auth session. I used getSession for this purpose. Is there a wrong way to retrieve the session in 'edge'? If so, what should I do instead?

Answer №1

It seems like you're attempting to verify in _middleware.js whether the current user is logged in or not, without using getSession().

Here's a workaround that I've implemented and tested locally (not yet in production):

export async function middleware(req) {

    const pathname = req.nextUrl.pathname

    const session = await getToken({ req: req, secret: process.env.NEXTAUTH_SECRET }); // Retrieving the session here

    // Protecting protected pages
    if (arrayOfProtectedPaths.includes(pathname)) {
        if (session === null) {
            return NextResponse.redirect("http://localhost:3008/spots/allSpots")
        }
    }

    // Preventing logged-in users from accessing registration and sign-in pages
    if (shouldNotBeUser.includes(pathname)) {
        if (session !== null) {
            return NextResponse.redirect("http://localhost:3008/spots/allSpots")
        }
    }
}

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

Guide to running several versions of a single Next JS application with distinct configurations simultaneously on a shared server

My goal is to run 2 instances of the NextJS app on the same machine with different configurations and ports. The first instance runs on port 3000, while the second runs on port 3001, and this setup functions correctly with the commands: next dev next de ...

What is the process for managing data synchronization in Redux-persist?

I developed an authorization application that writes data to AsyncStorage after a successful login. I now want to access this data through shared storage and am wondering how I can transfer or remove data synchronization with Redux-persist. ...

The declaration file for the module 'bootstrap/dist/js/bootstrap' could not be located

Currently, I am developing a Next.js application and have integrated Bootstrap for styling. However, I am encountering an error when trying to import the bootstrap.bundle.js file. I am facing the following error message: Could not find a declaration file f ...

Having issues with CSS animation keyframes not functioning properly in NextJS

Currently, I have a straightforward component in NextJS that is displaying "HI" upon loading. This component fades in when rendered, but I am facing an issue while trying to pass a prop to make it fade out. The problem lies in the fact that even though the ...

`Unable to upload spreadsheet file in xlsx format`

I'm currently working on implementing a feature to export data as xlsx files. I have been successful in exporting CSV and PDF formats, but encountered issues with the xlsx format due to dynamic imports. export const exportToXlsx = async ( gridElemen ...

Ways to implement the don't repeat yourself (DRY) principle in React JS with condition-based logic

https://i.stack.imgur.com/xkrEV.gif Here is a sample way to use the component: import React from "react"; import MyAvatars from "../../components/MyAvatar/MyAvatars"; const About = () => { return ( <MyAvatars ...

Upcoming: NextJS version 10 introduces enhanced i18n capabilities with the ability to customize folder names in

I am trying to create a multi-language website where I need to translate a specific folder differently for each language. The folder structure in question is as follows: pages/kennis/index.tsx I am having trouble figuring out how to translate the "kennis" ...

Creating a feature that allows users to edit the order of items within a MySQL

I am working on a project where I need to display a table of items that can be added, deleted, and reordered by the user. Initially, I planned to store these items in a MySQL database with an order column in the table. However, I realized this method is in ...

Discover the secrets of applying a custom theme to a specific page with the power of Next.js 13 appDir. Unleash the potential

I've successfully set up my website with the Next.js 13 appDir and am using the next-theme workaround for appDir, as discussed in this issue: https://github.com/pacocoursey/next-themes/issues/152 My goal is to apply a theme specifically to the home p ...

Is it necessary to write Higher Order Component in React as a function?

As I dive into learning React, the concept of Higher Order Components (HOCs) becomes clearer. Take for instance the following example extracted from React's official documentation: function withSubscription(WrappedComponent, selectData) { // ...a ...

Using capital letters with interpolated language keys

The issue: I'm currently facing a problem with i18next. It allows variable interpolation in strings, like "AddNew": "Add new {{item}}". However, I have a language where the grammar requires "{{item}}" to be the first word, as in "AddNew": "{{item}} t ...

Simulating server-side interactions in Node.js with TestCafe

I am currently working on a project where I need to figure out how to mock server-side requests. While I have successfully managed to mock client-side requests using request hooks, I am facing challenges when it comes to intercepting server-side requests ...

JWT - Effective strategies for enhancing the user experience for a returning logged-in user

My client authentication system involves storing a JWT in `localStorage` once the user is verified. However, I'm not satisfied with the current user experience when a returning user is redirected straight to a new page without warning. window.locatio ...

The loading component is displayed at the top of the page

In my project, I added a loading screen feature using a loader component in the _app.js file. function MyApp({ Component, pageProps }) { const [loading, setLoading] = useState(false) Router.events.on('routeChangeStart', (url) => { setLo ...

Error: The property 'children' is not found in type '{ children?: ReactNode; }'

I have been working on implementing the search bar feature from the provided link. Despite my efforts to match the types correctly, I keep encountering a TypeScript error. Homepage.tsx const [searchQuery, setSearchQuery] = useState(query || '' ...

Why are my images not displaying in Next.js when using Laravel API, even though the paths and configurations are correct? What could be the reason behind

I am currently working on a project that combines Next.js with a Laravel API. One of the functionalities of the project allows users to upload the title, description, and image to the database. Once uploaded, the images are stored in the storage/app/produ ...

How to pass props to customize styles in MUI5 using TypeScript

Currently, I'm in the process of migrating my MUI4 code to MUI5. In my MUI4 implementation, I have: import { createStyles, makeStyles } from '@material-ui/core'; import { Theme } from '@material-ui/core/styles/createMuiTheme'; ty ...

Optimizing File Transfers and Streaming Using Next.js and CDN Integration

As I work on developing a download system for large files on my website using Next.js and hosting the files on a CDN, I face the challenge of downloading multiple files from the CDN, creating a zip archive, and sending it to the client. Currently, I have i ...

When clicking on the Recipe button, it displays both recipes simultaneously instead of separately

When clicking on different recipe buttons, I am struggling to display only one recipe at a time instead of both at once. \\First Card <Card style={{ width: '18rem' }} className="Chicken"> <Card.Img variant ...