Is it possible to set up an automatic redirection to the Identity Provider sign-in page when accessing a protected page in Next.js using Auth.js?

Currently in the process of developing a web platform utilizing [email protected] and Auth.js([email protected]).

The provider has been configured with the given code, allowing successful signing in using the "Sign in" button.

auth.ts

import NextAuth from 'next-auth'
import Cognito from 'next-auth/providers/cognito'

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [Cognito],
})

app/login/page.tsx

import { auth, signIn } from '@/auth'

export default async function Login() {
  return (
    <form
      action={async () => {
        'use server'
        return await signIn('cognito')
      }}
    >
      <button type="submit">Sign in</button>
    </form>
  )
}

Challenges Encountered

Incorporating middleware to secure all pages and automatically redirect users to the Amazon Cognito(IdP) sign-in page is causing issues. The current code is failing to work as intended (remaining on protected pages without an active session and failing to redirect).

Is there a method to directly redirect to the Cognito sign-in page?

Note: While I am able to redirect users to /login within the application, I aim to streamline this process for user convenience.

middleware

import { signIn, auth } from "@/auth"

export default auth((request) => {
  if (!request.auth) {
    signIn('cognito')
  }
})

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico|login).*)"],
}

Error Log

ReadonlyRequestCookiesError: Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options
    at Proxy.callable (webpack-internal:///(middleware)/./node_modules/next/dist/esm/server/web/spec-extension/adapters/request-cookies.js:22:15)
    at signIn (webpack-internal:///(middleware)/./node_modules/next-auth/lib/actions.js:53:65)
 ⨯ unhandledRejection: ReadonlyRequestCookiesError: Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options
    at Proxy.callable (webpack-internal:///(middleware)/./node_modules/next/dist/esm/server/web/spec-extension/adapters/request-cookies.js:22:15)
    at signIn (webpack-internal:...

Answer №1

there seems to be an issue:

Oops! Cookies can only be modified in a Server Action or Route Handler.

It appears that the error occurred because you attempted to perform signIn within a server-component. Remember, cookies can be accessed on the server side but can't be set or deleted there. Convert your signin component into a client component to resolve this error.

Regarding the requested middleware behavior, if you wish to secure routes at the middleware level, you must provide an array of protected routes to the middleware. Then, compare the current pathname with each path in the protected_routes_array to ensure route protection.

import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";
export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const protectedRoutes=['/route1', '/route2' ];
  const token = await getToken({ req: request });
  if (token == null && protectedRoutes.includes(pathname)) {
    return NextResponse.redirect(
      new URL(
        "/signin",
        request.url
      )
    );
  }
}

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

Utilize Typescript Functions to Interact with GeoJSON Data in Palantir Foundry

Working on a map application within Palantir utilizing the workshop module. My goal is to have transport routes showcased along roads depending on user inputs. I am familiar with displaying a route using GeoJSON data, but I'm wondering if there is a w ...

"Encountering a Syntax Error When Using request.post in Dojo Framework on Button Click

Here are three questions to consider: 1) What strategies can be utilized to streamline this code and reduce nesting and quote-related complications? 2) Are there any suggestions for addressing the parsing error mentioned below? I've already tested sep ...

JavaScript: Harnessing the power of scripts to handle dynamically loaded data via AJAX

I am currently working on a webpage where I need to display various events using AJAX and PHP. One requirement is that when a user clicks on the "view event" link at the bottom of each event, a modal window should pop up. To achieve this functionality, I h ...

Warning: The use of jQuery load to trigger a Synchronous XMLHttpRequest on the main thread is now considered deprecated

$('#in-view-contents').load("/browse/".concat(selectedId), function(responseData){ var contentsLabelEl = document.getElementById("refined-contents-container"); contentsLabelEl.style.display = "block"; var arrayOfReloadScripts = ["/js/ ...

Dealing with AngularJS: Issue arises when attempting to inject $modal into a controller nested within a directive

Our team has implemented a custom directive that wraps around a checkbox and utilizes transclusion to inject content into it. Here is an example of the setup: somecheckbox.js angular.module('namespace.directives') .directive('someCheckbox& ...

Select several options as chosen when the page is loaded

Does anyone know how to activate the function that selects values from an array and triggers a hide action after the page reloads? The array is stored in local storage. When I use $('#hide_col').val('.row'+hide); inside the function, on ...

Mastering the use of useMasterKey in Parse with Node.js: A guide

Greetings everyone, I have developed my app using parse.com but now I need to utilize the master key as some users have administrative roles. Initially, I attempted to use the JS SDK but was advised to switch to Cloud Code. So, I tried using Express and ...

Looking to retrieve the mouse coordinates using JavaScript

How can I use JavaScript to track the mouse position on a canvas? Upon visiting this page: http://billmill.org/static/canvastutorial/mouse.html They provide this code snippet: function initializeMouse() { canvasMinimumX = $("#canvas").offset().left; ...

The JavaScript code malfunctions when I introduce a new HTML tag

I am attempting to create a simple photo gallery using PhotoSwipe. However, I have encountered an issue where certain functions like Previous and Next buttons stop working when I add new HTML elements. Here is the original code: <div class="my-gallery ...

Conflict between jquery and hoverIntent libraries

I've encountered an issue with a website that was functioning properly until we added a new form to a specific page. The form, created by another person, utilizes javascript/jQuery for processing. Since adding this form, it has caused the majority of ...

browsing through a timeline created using HTML and CSS

I am currently working on a web project that involves creating a timeline with rows of information, similar to a Gantt chart. Here are the key features I need: The ability for users to scroll horizontally through time. Vertical scrolling capability to na ...

Enhancing performance with React.memo and TypeScript

I am currently developing a react native application. I am using the Item component within a flatlist to display data, however, I encountered an error in the editor regarding the second parameter of React.memo: The error message reads: 'Type 'bo ...

Unable to render Row using MySQL in conjunction with ReactJS

Recently, I started working on developing a table using ReactJS on the FrontEnd, NodeJS on the BackEnd, and MySQL for the database. I am trying to retrieve data based on a Select request using the primary key (Code) from the list. https://i.sstatic.net/tXP ...

Access the data from a JSON object within a v-select menu

<v-form :model='management'> <v-flex xs3 sm2 md3> <div class="form-group> <v-select :items="days" item-text='text' item-value='text' placeholder="MM" single-line attach v- ...

Guide on populating text boxes in a form automatically using ngFor?

As a beginner Angular developer, I am looking to automatically fill in text boxes in a form, specifically 10 text boxes (10 rows) using the ngFor directive. In my research on ngFor examples, I have noticed that most of them focus on populating a list base ...

What is the best way to isolate the text before a particular segment within a string, excluding any blank spaces?

Is it possible to use vanilla JavaScript in order to extract the first string value directly to the left of a specified portion of a longer string, excluding any blank spaces? Consider the following string: 1 hr 30 min How could you extract the 1 located ...

Typescript's definition file includes imports that can result in errors

Occasionally, typescript may generate a definition file with code like the following, leading to compile errors: // issue.ts import { Observable } from 'rxjs'; class Issue { get data() { return new Observable(); } } // issue.d.ts class ...

Invoke the method in customButton component of fullcalendar

I've integrated a custom button into my fullcalendar: ngOnInit() { this.calendarOptions = { customButtons: { custom1: { text: 'Add event', click() { this.openModal(); } } }, height: 600, editable: t ...

Tips for triggering window load event on a particular page

I need to trigger the windows.load event on a specific page. Currently, I have set it up like this: $(window).load(function(){ if(document.URL == "/car-driving.html") { overlay.show(); overlay.appendTo(document.body); $('.popup' ...

Submitting the form without utilizing Ajax, but instead sending data directly to a PHP script

I've encountered an issue while posting a form to a PHP file using AJAX. Despite my efforts, the form is bypassing AJAX and posting directly to the PHP file. Here is my form: <form id="editform" name="editform" action="ajaxeditform.php" method= ...