Redirect user to new page upon successful login using next-auth middleware

I recently implemented the next-auth middleware to protect all pages on my website. I followed the official documentation on next-auth (next-auth) and verified that it successfully redirects users who are not logged in.

However, I encountered an issue where even when I am logged in, it keeps redirecting me to the login page.

If anyone can help me diagnose what I might have done wrong, I would greatly appreciate it.

[...nextauth].ts

import NextAuth, { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import client from "@/libs/server/client";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { Session } from "next-auth/";

interface UserSession extends Session {
  id: string;
}
export const authOptions: NextAuthOptions = {
  // Configure one or more authentication providers
  adapter: PrismaAdapter(client),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
  callbacks: {
    session: ({ session, user }) => {
      (session as UserSession).id = user.id;
      return session;
    },
    redirect: ({ url, baseUrl }) => {
      return baseUrl;
    },
  },
  secret: process.env.NEXTAUTH_SECRET,
  pages: {
    signIn: "/enter",
  },
};

export default NextAuth(authOptions);

middleware.ts

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

export const config = {
  matcher: ["/mypage","/with", "/product/:path*"],
};

Answer №1

One of my successful strategies was implementing session handling and incorporating JWT into the callback process.

import NextAuth, { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import client from "@/libs/server/client";
import { PrismaAdapter } from "@next-auth/prisma-adapter";

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(client),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
  callbacks: {
    jwt({ token, account, profile }: any) {
      if (account) {
        console.log("token", token);
        token.accessToken = account.access_token;
        token.id = profile.id;
      }
      return token;
    },
    session({ session, token }: any) {
      session.accessToken = token.accessToken;
      session.id = token.sub;
      return session;
    },
    redirect({baseUrl}) {
      return baseUrl;
    }
  },
  secret: process.env.NEXTAUTH_SECRET,
  session: {
    strategy: "jwt",
  },
  pages: {
    signIn: "/enter",
  },
};

export default NextAuth(authOptions);

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

The power of the V8 JavaScript engine: Understanding v8::Arguments and the versatility of function

I have created a Node.js addon that wraps a C++ standard library element std::map<T1,T2>. The goal is to expose this map as a module with two primary functions: Set for adding new key-value pairs and Get for retrieving values by key. I want to create ...

Synchronous loop in Javascript

Is there a method to execute codes asynchronously within a for loop? In this scenario, events ranging from day x to y need to be inserted into the calendar using a for loop. However, the current loop is taking too long, as it has to cover all the days fro ...

Angular template driven forms fail to bind to model data

In an attempt to connect the model in angular template-driven forms, I have created a model class and utilized it to fill the input field. HTML: <div class="form-group col-md-2 col-12" [class.text-danger]="nameCode.invalid && nameCode.touched ...

Notification prompt when removing items

I currently have a table set up with a delete <a> tag that allows users to delete data. I would like to add a confirmation message asking the user if they are sure they want to delete before proceeding. I attempted to achieve this using JavaScript bu ...

Enhancing Type Safety in TypeScript with Conditional Typing within Array reduce()

In my codebase, I've implemented a function named groupBy (inspired by this gist) that groups an array of objects based on unique key values provided an array of key names. By default, it returns an object structured as Record<string, T[]>, wher ...

Create a bookmark system on an HTML page by utilizing the existing heading tags and implementing Javascript

Looking to implement a bookmark system using the headings within my HTML document, based on heading hierarchy. Unfortunately, my attempts have not been successful so far. https://i.stack.imgur.com/CdXjw.png I envision my bookmarks looking something like t ...

Accessing a PDF document from a local directory through an HTML interface for offline viewing

As I work on developing an offline interface, I'm encountering an issue with displaying a PDF file when clicking on an image. Unfortunately, the code I have in place isn't working as intended. Can someone please assist me with this problem? Below ...

What could be causing the error when my file is running?

Whenever I attempt to run a file using the command node database.ts, an error pops up. Can someone help me identify what's wrong with my syntax? This is how the file appears: import { Sequelize } from 'sequelize-typescript'; export const ...

Change the anchor text dynamically with JQuery

The page contains href links with incomplete text. For example, the link text displayed on the page is "link1", but it should actually be "link1 - Module33". Both the page text and actual text start with the same initial text ("link1" in this case). I retr ...

"Looking for a way to automatically close the <li> tag in Vuejs when clicked outside

clickOutside: 0, methods: { outside: function(e) { this.clickOutside += 1 // eslint-disable-next-line console.log('clicked outside!') }, directives: { 'click-outside': { ...

Updating state with new data in React: A step-by-step guide

Recently, I delved into the world of reactjs and embarked on a journey to fetch data from an API: constructor(){ super(); this.state = {data: false} this.nextProps ={}; axios.get('https://jsonplaceholder.typicode.com/posts') ...

Uploading videos to a single YouTube channel using the YouTube Data API

I have been tasked with creating a node js app for a select group of individuals who need to upload videos. However, our budget is quite limited and we are unable to afford cloud storage services. I am curious if it would be feasible to create a key syste ...

Interactive webpages with dynamic HTML content, similar to the design of popular platforms such

Explore the source code of Dropbox's homepage or any Soundcloud page. They utilize various scripts and minimal pure HTML content (article, main, p, div). This method of generating pages is referred to as dynamic content/HTML. The main function seems ...

Experiencing difficulties with the onClick functionality on a registration form

Recently started learning React, so I apologize if the solution seems obvious. Currently working on a registration form that should create a new account upon submission using AJAX. Although I understand that I need to use onChange to gather the submitted i ...

Encountering problem with JSON in the bodyParser function

I've encountered an issue while sending data from my React component using the Fetch API and receiving it as JSON on my Express server. When I try to parse the data using the jsonParser method from bodyParser, I only get back an empty object. Strangel ...

Changing the name of a file using NPM

Is there a way to change the name of a specific file in npm scripts? I need to modify files for distribution, but they must have different names than the original... I attempted using orn, however it only works on the command line and not as an npm script ...

How to extract data from a span element using AngularJS

Combining input values to create a cohesive string: <input ng-model="first"> <input ng-model="second"> <span ng-model="result">{{first}} and {{second}}</span> Is there a way to retrieve the resulting string from JavaScript? I&apos ...

"Using Node.js to create a simulated mobile environment: a step-by-step guide

I am seeking a way to replicate the functionalities of a mobile browser using Node.js. This means that all mobile browser features should be accessible on the client-side, even if they are simulated. The goal is for webpages to believe they are being load ...

Exploring the realm of Typescript custom decorators: The significance behind context

I'm currently working on a custom decorator that will execute decorated functions based on RxJS events. Everything seems to be going well so far, but I'm facing an issue when the function is executed: the context of the this object is lost. I&a ...

How can I use Angular to dynamically open a video that corresponds to a clicked image?

I need assistance with a functionality where clicking on an image opens a corresponding video on the next page. The issue is that all images have the same ID, making it difficult to link each image to its respective video. Below is the data I am working ...