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

Ways to verify if a user is authenticated without relying on request.session

I am currently developing a web application using Express, Docker, and following a Three-layered architecture. In my app, I store user login information in a session and have blogposts as a key resource. To retrieve the blogpostId from the database in the ...

Using Primeng to implement pagination and lazy loading in a dataView

Looking for a way to search through product data with filters and display it using primeng dataview? Consider implementing pagination in your API that pulls products from the database page by page. Set the products array as the value in dataview so that wh ...

Adjusting the selection in the Dropdown Box

I've been attempting to assign a value to the select box as shown below: <dx-select-box [items]="reportingProject" id="ReportingProj" [text]="reportingProject" [readOnly]="true" > ...

Establishing a default value for Image src within next.js would ensure that a placeholder image

I have been struggling to set a default value for the image src in the Image component within my next.js project. I have not been able to find any options to handle the scenario where the server responds with a status code of 400. Currently, I am receiving ...

Exploring the functionalities of arrays in Typescript: A beginner's guide

Currently, I am working on a react project and building a store within it. Below is the code snippet I have implemented: import React, { useReducer, useEffect } from 'react'; import { v4 as uuid } from 'uuid'; import { Movie, MoviesAct ...

The wrapAll() method can be used to wrap list items within two columns

I am looking to group multiple li elements within two div containers by using jQuery's wrapAll method. The challenge lies in the fact that these items are rendered within a single <ul> element via a CMS. Here is the current setup: <ul> ...

I possess a list of unique identifiers and require the ability to either update an existing object within an array contained in a MongoDB document, if it exists,

I am facing a challenge in updating a specific element within an array in a MongoDB document. I have multiple IDs of that array and need to update the matching element using those IDs. data= [ { "planId" : "plan_FVNvrmjWT7fRDY", "startTime": ...

How can I ensure that my rendering only occurs after a full input has been entered? Implementing a delayed render() in ReactJS

Im working on a form that includes Controlled Component text inputs: <input type="text" onChange={(e) => this.props.changeBusiness(e)}/> I'm thinking of rendering the above text input in a separate component. It would be great if I could re ...

When implementing a v-for loop in Vue.js with Vuetify and using v-dialog components, the click event may be overwritten for all v-dialogs except

My app features the utilization of a Vuetify v-dialog within a v-for loop. However, I am encountering an issue where clicking on any chip within the loop triggers the click event for the last v-chip, instead of the specific one being clicked. It appears t ...

The timing of the JavaScript dialog with the AJAX call is off-kilter

Encountering an issue with a JavaScript script designed to showcase a JQUERY dialog box based on a C# ViewModel. Within a repeater, there is an ASP drop-down menu displaying 'Registration Date' details. The objective is for the JavaScript dialog ...

Mongoose managing diverse connections

Currently, I am working with Node.Js 8.6 and Mongoose 4.11, managing multiple database connections using mongoose.createConnection. Upon exploring the connections property within the mongoose object (an array that stores established connections), I am curi ...

To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function: export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) { // Beginning point: // [key1,key2,key3], // [value1,value2,value3] // // End point: { // key1: val ...

Having trouble retrieving input field values with Angular.js

I am struggling to access the input field values in my Angular.js application. Below is the code snippet I am using: <div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon ndrftextwidth text-right" style="width:180px"& ...

Angular-ui typeahead feature allows users to search through a predefined

I recently developed a typeahead feature using the angular-ui library. Here is the current HTML for my typeahead: <input name="customers" id="customers" type="text" placeholder="enter a customer" ng-model="selectedCustomer" uib-typeahead="customer.fir ...

Is there a universal method to disregard opacity when utilizing jQuery's clone() function across different web browsers?

I've encountered a situation where I need to allow users to submit a new item to a list within a table, and have it smoothly appear at the top of the list. While using DIVs would make this task easier, I am working with tables for now. To achieve thi ...

Is it possible for JavaScript to access and read a local file from a web page hosted locally

I am interested in using html, css, and javascript to develop a user interface for configuring a simulation. This interface will be used to generate a visualization of the simulation and an output parameters file based on multiple input files. It is impor ...

"Enhance your development experience with the TypeScript definitions for the Vue 2 plugin

Currently, I am utilizing VSCode alongside TypeScript classes for developing Vue 2 components. You can check out more information at: vuejs/vue-class-component. Within my present project, I make use of plugins like vue-i18n for handling translations of la ...

Tips for integrating JavaScript libraries with TypeScript

I'm looking to add the 'react-keydown' module to my project, but I'm having trouble finding typings for it. Can someone guide me on how to integrate this module into my TypeScript project? ...

Storing audio files in Firebase Cloud Database and displaying them in React js + Dealing with an infinite loop problem

Lately, I've been encountering a persistent issue that has proven to be quite challenging. Any assistance would be greatly appreciated. Thank you in advance. The objective is to create a form that allows for the easy addition of new documents to the ...

Dependency tree resolution failed during VUE installation

After pulling my project from another computer where it worked fine, I encountered an error when trying to npm install on this machine. Can someone please provide some guidance on how to resolve this issue and prevent similar problems in the future? npm ER ...