Encountering issues with Next.js 13 middleware functionality

On several pages of my website, I require the user to be logged in. To achieve this, I have implemented middleware to check if the user is authenticated and blocked access to certain pages until the user logs in. Below is the code snippet from my file:

export {default} from "next-auth/middleware";

export const config = {
    matcher: ["/api/:path*", "/new"]
}

Even though a user is already logged in and tries to access the /new route, they are prompted to login again. The expected behavior is for authenticated users to access the route without re-logging in. The issue seems to be with the /api/* path.

I am using Prisma as the adapter for authentication. Here is my next-auth configuration file:

// /api/auth/[...nextauth]/options.ts
import { prisma } from "@/lib/database";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { type NextAuthOptions } from "next-auth";
import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  secret: process.env.NEXTAUTH_SECRET,
  session: {
    maxAge: 30 * 60,
  },
  debug: process.env.NODE_ENV === "development" ? true : false,
  pages: {
    signIn: "/auth/login",
  },
  providers: [
    GithubProvider({
      clientId: process.env.APP_GITHUB_CLIENT_ID as string,
      clientSecret: process.env.APP_GITHUB_CLIENT_SECRET as string,
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
};

I import this configuration into /api/auth/[...nextauth]/route.ts as shown below:

import NextAuth from "next-auth/next";
import { authOptions } from "./options";

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

Here is my schema.prisma file:

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider     = "mysql"
  url          = env("DATABASE_URL")
  relationMode = "prisma"
}

model Todo {
  id               String   @id @default(cuid())
  todo_name        String
  todo_description String?
  completed        Boolean? @default(false)
  createdAt        DateTime @default(now())
  updatedAt        DateTime @updatedAt
  user             User?    @relation(fields: [userId], references: [id])
  userId           String?

  @@index([userId])
}

<!-- More model definitions -->

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

Your assistance on this matter would be greatly appreciated.

Answer №1

Discovered a successful solution

By changing the session strategy to jwt, the workaround is achieved

Make sure to include this segment in your authOptions

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  secret: process.env.NEXTAUTH_SECRET,
  session: {
    maxAge: 30 * 60,
    strategy: "jwt", // <- this solves the issue
  },
  debug: process.env.NODE_ENV === "development" ? true : false,
  pages: {
    signIn: "/auth/login",
  },
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_CLIENT_ID as string,
      clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
};

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

Angular routing is showing an undefined ID from the snapshot

When a user attempts to update a student, I pass in the student ID. The update successfully redirects to the updateStudent page and displays the student ID in the browser link. However, within my app component, it shows as undefined. Student View componen ...

Type 'Object' cannot be assigned to type 'Produit' as per error code TS2322

As a newcomer to Angular, I've been encountering the following error for the past 5 days: "ERROR in src/app/modifier-produit/modifier-produit.component.ts(23,7): error TS2322: Type 'Object' is not assignable to type 'Produit'. Th ...

The object's type remains a mystery

While working on implementing jwt authentication in Ionic, React with TypeScript, I faced a typescript error when trying to add a check in my App.tsx file after successful implementation. The error stated: Object is of type 'unknown' Below is ...

Changing the Express.Request.user type from optional User to required User for authorized routes: A guide

Currently, I am developing a server using Express and Typescript. I have integrated passport js for authenticating the routes I have set up. However, one issue that I encounter is that Express.Request.user is defined as Express.User | undefined. This means ...

My Next.js app's iframe is being blocked by Chrome. Any suggestions on how to resolve this issue?

I have encountered an issue while trying to display an iframe in my Next.js application. Although the iframe is functioning properly in Firefox, it is being blocked in Chrome. The process of rendering the iframe seems straightforward. Below is the comple ...

Transforming Javascript into Typescript with node modules in Visual Studio 2015

After developing a JavaScript web app using npm and webpack, I successfully converted all the .js files to .ts using the PowerShell command found here. Now, I am looking to transition to a VS2015 TypeScript project but struggling to find guidance on how ...

FormArray does not properly handle invalid input focus

Although everything functions correctly with a regular FormGroup, the issue arises when dealing with a FormArray as it fails to focus on the invalid input. Here is how my form is initialized: initForm() { this.parentForm= this.fb.group({ childFo ...

I am trying to incorporate the tailwind styling of "active:border-b-2 active:border-blue-500" into my next.js project, but unfortunately, it doesn't seem to be

This is the custom Tailwind CSS styling I would like to apply: import React from 'react' function HeaderIcon({Icon}) { return ( <div className="flex items-center cursor-pointer md:px-10 sm:h-14 m ...

error message: when running `prisma generate`, the installed package `@tsed/prisma` cannot be located

Attempting to integrate Ts.Ed v7.35 with prisma v5.2 by following this official tutorial. Upon running npm install, encountered an error during npx prisma generate: Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma Erro ...

Interacting with icons using TouchableOpacity and onPress functionality

I am attempting to implement onPress functionality for icons using TouchableOpacity. However, when I click on the icon, nothing happens and there are no console logs displayed. I have also tried enclosing the icon within an additional View, but that appro ...

Unit test code coverage was exclusively discovered in Next.js using Cypress

I've been attempting to implement code coverage in Cypress by following this helpful tutorial In order to do so, I added both @cypress/code-coverage and babel-plugin-istanbul to the package.json file as seen below { "name": "quiz", "private": tru ...

Is there a way for me to showcase the number of items in my shopping cart on all pages within my React/Next.js app?

I have been struggling with a persistent issue in my nextjs eCommerce application for over a week now. The project is part of a web dev BootCamp that I am currently enrolled in, and I need to submit it by the end of this week. The problem revolves around t ...

Utilizing precise data types for return values in React hooks with Typescript based on argument types

I developed a react hook that resembles the following structure: export const useForm = <T>(values: T) => { const [formData, setFormData] = useState<FormFieldData<T>>({}); useEffect(() => { const fields = {}; for (const ...

GitLab's CI/CD pipeline is unable to detect ts-node even though it has already been

As a newcomer to setting up GitLab CI, I am currently venturing into implementing a small web application using the MERN pipeline (MongoDB, express, react, Nodejs). My goal is to create a simple project akin to google drive where users can store and manage ...

What is preventing me from accessing a JSON file on Vercel while utilizing Next.js SSR?

I am currently working on a basic Next.js project with three main files. My goal is to populate the index page with data from a JSON file. Interestingly, when I deploy the project to Vercel using getStaticProps, everything functions correctly. However, up ...

Encountering an error in TypeScript: Attempting to define type files for a third-party library triggers the TS2709 error when attempting to use the 'Optional' namespace as a type

Currently, I'm in the process of creating type files for a third-party library called optional-js. The structure is as follows: index.js var Optional = require('./lib/optional.js'); module.exports = { empty: function empty() { ...

Open the JSON file and showcase its contents using Angular

I am attempting to read a JSON file and populate a table with the values. I've experimented with this.http.get('./data/file.json') .map(response => response.json()) .subscribe(result => this.results =result, function(error) ...

Is it possible for NextJS to retrieve server-side props only once?

My goal is to execute a server-side data query only once when a user logs into a website. The retrieved data will be transmitted to the frontend and stored in a context so that any further page navigations using next/link will retain this existing data. T ...

What exactly does the syntax (<any> new Classname) accomplish in terms of purpose and behavior?

In the code snippet below, a new instance of ClickerApp is being created with a PlatformMock and MenuMock as parameters: let instance = new ClickerApp((<any> new PlatformMock), (<any> new MenuMock)); This code example is taken from the follow ...

Creating a dynamically generated sitemap route in NextJS

I am struggling to generate a dynamic router for the sitemaps that are accessible via the following URLs: example.com/sitemap-0.xml example.com/sitemap-1.xml My attempt was to create a page using the following file structure: [sitemap].xml.js Unfortunat ...