Securing your folders with Next Auth middleware

I am currently developing a NextJS application and have implemented routers at pages/dashboard/* that I need to secure. My goal is to restrict access to these routes only to authenticated users. I am utilizing Prisma for data management, with Google as the authentication provider. All configurations are set up correctly. This is my middleware.ts

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

export const config = { matcher: ["/dashboard"] }

The setup is quite straightforward. Here is my [...nextAuth] file

import NextAuth, { NextAuthOptions } from "next-auth" import GoogleProvider from "next-auth/providers/google" import { PrismaAdapter } from "@next-auth/prisma-adapter" import { prisma } from "@/lib/db/prisma"

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code",
        },
      },
    }),
  ],
}

export default NextAuth(authOptions)

I have stored secrets in a .env.local file and also created a NEXTAUTH_SECRET locally. However, I am encountering an issue where upon navigating to the dashboard, the user gets redirected to the login page. Even after successful login, the dashboard remains inaccessible and prompts for login repeatedly. Upon examining, I observed that while the useSession function returns data in the browser, the token or session on the server side appears to be null. I am using Next 13.2.4 and Next Auth ^4.20.1, but despite trying various solutions suggested in similar questions, none seem to resolve the issue and I am unable to access the dashboard. Any assistance would be greatly appreciated. Thank you.

Answer №1

After some troubleshooting, I was able to discover the solution to the issue at hand. For anyone facing a similar predicament, here is what worked for me:

 session: {
    strategy: "jwt",
  },

Implementing this change into the next auth options resolved the problem entirely.

Answer №2

Make sure to include NEXTAUTH_SECRET in the authOptions section.

 export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code",
        },
      },
    }),
  ],
session: {
    strategy: 'jwt'
},
secret: process.env.NEXTAUTH_SECRET

}

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

Retrieving parameters from the URL in Angular

I'm facing an issue with my app. I am currently using a factory to manage data for two controllers. When I click on a link that redirects me to another view with a specific URL, I want to reuse the last tag in the URL by slicing it like this: window. ...

When I implement JavaScript on my website, my HTML content does not show up

Whenever I try to fetch content from a specific URL using AJAX and a script, my HTML content does not show up. In other words, the table element is not displayed on the page. Instead, I am able to retrieve data from the specified URL and display it in an a ...

Illustrating SVG links

I'm working on a basic svg animation project where I want to create a simple shape by animating a line under a menu link. The goal is to have a single line consisting of a total of 7 anchors, with the middle 3 anchors (each offset by 2) moving a few p ...

Separate the express node js into a pair

I'm attempting to divide a code into two parts using express. Here is how I approached it: app.js var express = require('express'); var app = express(); var stud = require('./grades'); var port = process.env.PORT || 3000; stud. ...

Cannot trigger a click event on nginclude in AngularJS

I have a question regarding including a new page using the nginclude directive. The click event defined in the included page is not working properly. Main Application: <div ng-app=""> <input type="text" ng-model="ss"/> <div ...

Press the button in an HTML document to activate JavaScript

What could be the issue with my code? I have a button in HTML <a class="btn btn-warning btn-mini publish-btn" href="#" data-rowid="@computer.id" data-toggle="modal" data-target="#myModal">Outdated</a> and my modal <fieldset style="text-al ...

The Value of Kendo Data

Below is my current kendo code snippet: <script> $("#dropdowntest").kendoDropDownList({ optionLabel: "Select N#", dataTextField: "NNumber", dataValueField: "AircraftID", index: 0, ...

Designing a sequential bar graph to visualize intricate data using AmCharts

I received the following response from the server in JSON format: [{ "data1": { "name": "Test1", "count": 0, "amount": 0, "amtData": [ 0,0,0,0 ], "cntData": [ 0,0,0,0 ], "color": "#FF0F00" }, "data2": { ...

Data vanishing in upcoming authentication session in test environment

I have encountered an issue with next auth in my next.js project. During development, the session data is lost if the server refreshes or if I switch to another tab and return to it. This forces me to sign out and then sign back in to restore the session d ...

Having trouble retrieving data when updating a user in ExpressJS

Trying to update an experience array in the User model with new data, but facing issues with saving the data in the exec function. As a result, unable to push the new data to the array on the frontend. Here is the current code snippet: router.post('/ ...

Having trouble exporting an object from a different JavaScript file in Node.js

I have been attempting to make the getCurrentSongData function retrieve the songdata object passed in from the scraper. However, I am encountering the following output: ******************TESTING**************** c:\Users\(PATH TO PROJECT FOLDER)& ...

display the designated image as a priority

I am designing a loading screen for my website that includes the loading of multiple images, scripts, and other elements. While the HTML and CSS part is working well, I need to ensure that the "loading..." image is loaded before anything else on the page. ...

I am encountering an issue where I am unable to successfully fetch a cookie from the Express backend to the React

const express = require("express"); // const storiesRouter = require("./routes/storiesRouter") // const postsRouter = require("./routes/postsRouter"); // const usersRouter = require("./routes/usersRouter"); const cors = require("cors"); const cookieParser ...

Retrieve the current height of the iFrame and then set that height to the parent div

Within a div, I have an iFrame that needs to have an absolute position for some reason. The issue is that when the iFrame's position is set to absolute, its content overlaps with the content below it. Is there a way to automatically adjust the height ...

Effortlessly retrieving the id attribute from an HTML tag using jQuery

Currently, I am encountering an issue with a code snippet that is designed to extract the value from an HTML tag. While it successfully retrieves a single word like 'desk', it fails when attempting to do so for an ID consisting of two or more wor ...

Node.js express version 4.13.3 is experiencing an issue where the serveStatic method is not properly serving mp3 or

I am currently utilizing Express 4.13.3 along with the serve-static npm module to serve static assets successfully, except for files with mp3 or ogg extensions. Despite reviewing the documentation, I have not come across any information indicating that thi ...

Change the value of the material slide toggle according to the user's response to the JavaScript 'confirm' dialogue

I am currently working on implementing an Angular Material Slide Toggle feature. I want to display a confirmation message if the user tries to switch the toggle from true to false, ensuring they really intend to do this. If the user chooses to cancel, I&ap ...

Is it possible to determine the time format preference of the user's device in Angular? For example, whether they use a 24-hour system or a 12-hour system with AM

In Angular, is there a way to determine whether the user's time format is set to 24-hour or 12-hour system? Any help would be greatly appreciated. Thanks! ...

I am experiencing an issue with the HTML5 video tag as it is not displaying the

Having trouble playing a user-uploaded video using the <video tag. The video doesn't seem to load into the DOM properly. Here's the code snippet: function Videos ({uploadedFiles}){ if (uploadedFiles) { console.log(uploadedFile ...

When submitting the club form, my goal is to automatically generate a club admin within the user list in activeadmin

My dashboard.rb setup looks like this: ActiveAdmin.register_page "Dashboard" do menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") } content title: proc{ I18n.t("active_admin.dashboard") } do # form render 'form' # Thi ...