Guide to logging in using REST/API with a Next.js application

Issue: I am facing a challenge integrating with an existing repository that was created using Next.js. The task at hand is to enable users to sign in to the application through a specific endpoint or URL. To achieve this, I have been attempting to utilize the signIn function within NextAuth.js, but it consistently generates an error stating

ReferenceError: window is not defined
.

Testing Strategy

  1. Include a CredentialsProvider in the [...nextauth].tsx file:
const providers: Provider[] = [
  
..., //exisiting providers

  CredentialsProvider({
    id: "jwt_auth",
    name: "JWT-Auth",
    credentials: {
      email: { label: "Username", type: "text"},
      password: { label: "Password", type: "password" },
    },
    async authorize(credentials, req) {
      return {
        id: "usr123",
        username: "testUser",
      };
    },
  }),
];
  1. In the /web/pages/api/auth/jwt.js file
import { NextApiRequest, NextApiResponse } from "next";
import { signIn } from "next-auth/react";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  await signIn<"credentials">("jwt_auth", {
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b3f2e383f0b2e332a263b272e65282426">[email protected]</a>",
    password: "myPassWord",
    redirect: false,
  });

  res.status(201).json({ message: "Logged in user" });
}

The current setup involves creating mock endpoints/functions that simulate a successful scenario to observe how the process unfolds. Despite these efforts, when sending GET/POST requests to /api/auth/jwt, an error is triggered indicating

ReferenceError: window is not defined
. This suggests that the functionality of the signIn method may rely on having a user interface.

Inquiry(s): What would be the best approach for implementing API-based sign-in functionality? Is it necessary to develop a workaround by crafting an endpoint that returns HTML content in order to facilitate the sign-in process?

Answer №1

Within our jsx code, we utilize the signIn function to kick off the signIn process. This functionality operates similarly to the redux-saga library, initiating the process on the client side while the next-auth library handles the backend operations.

import { signIn } from "next-auth/react";

// Execute this code inside your submitHandler or onClick handler
await signIn("credentials", {
      // To prevent automatic redirection upon signin failure, set redirect to false
      email,
      password,
    });

This action triggers the execution of the authorize function defined in your codebase. The role of this function is to access the database and validate user credentials. Upon successful verification, the function should return the corresponding user object. Following this operation, next-auth employs two callback functions.

CredentialsProvider({
  // Creates input fields accessible at http://localhost:3000/api/auth/signin
  credentials: {
    username: {
      label: "Email",
      type: "email",
      placeholder: "placeholder",
    },
    password: { label: "Password", type: "password" },
  },
  async authorize(credentials) {
       // Perform database queries and validation here
 }}),
],
callbacks: {
  jwt: async ({ token, user }) => {
    user && (token.user = user);
    return Promise.resolve(token);
  },
  session: async ({ session, token }) => {
    // Modify session properties as needed
    session.user = token.user;
    return Promise.resolve(session);
  },
},

To enter your credentials and authenticate yourself, navigate to the api route "http://localhost:3000/api/auth/signin"

https://i.stack.imgur.com/xp9sa.png

Comprehensive guide for setting up next-auth4

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

What is the best way to invoke a function that is saved in an array of options while using setTimeout() within an AJAX callback?

Below is the pertinent code snippet: success: [ setTimeout(function () { ajax.success }, 250), //... An interesting observation I made is that I am able to invoke ajax.success from inside the success ...

Can someone explain what logForm.$invalid.$setValidity is all about?

The code snippet can be found here I am a beginner in this field and currently studying a piece of code. I am having trouble understanding the logForm.$invalid.$setValidity line. I have searched online but couldn't find any information about it. The ...

Interactive input field designed for modifying, adding, and removing data in MySQL

I am working on a project where I have a simple form. However, I need to dynamically change the form action from insert to update within the same page. Additionally, I also want to display the values on the same page. Within my code, I have set up the up ...

Obtain GPS coordinates (latitude/longitude) from a Google map by dropping a marker on the

Is there a straightforward script that can load a Google Map and, when clicked, display a marker that saves the latitude and longitude values to a variable? Does anyone know if there is an existing PHP solution for this functionality? Appreciate any help ...

Unable to display text overlay on image in AngularJS

I am experiencing an issue with displaying captions on image modals. .controller('HomeController',['dataProvider','$scope','$location', '$modal', '$log', 'authService', function ...

Looking for a solution to the problem: Module 'import-local' not found

internal/modules/cjs/loader.js:596 throw err; ^ Error: Cannot find module 'import-local' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15) at Function.Module._load (internal/modules/cjs/loader.js:520:25) Encoun ...

Provide details on the final parameters

After creating my discord.js bot, I had the idea to implement a translator feature. To achieve this, I need to extract the last argument from incoming messages. client.on("message", async (message, args) => { if (message.content.startsWith(` ...

Steps to displaying a genuine Docx file within a Material CardMedia

Currently, I am facing an issue with positioning a docx file in my app. Interestingly, jpg and mp4 files are displaying correctly, but the docx file is not positioned as expected. If you want to try it out, simply open a doxc file. In the FileContentRend ...

Deployment is triggered by Contentful and Azure Static Web Apps working together

I recently set up a next.js application on Azure static web apps, and I have successfully automated the build process on GitHub using GitHub Actions. However, my next task is to configure changes made on contentful to trigger a build on Azure. As someone ...

Discover the best way to reference a JavaScript variable within an HTML form textfield

I'm having trouble with a script that is supposed to display the selected value from a drop down list in a text field on an HTML form. When I select an option, the value is not appearing in the text field. Can someone please assist me with this issue? ...

unable to log out firebase user

Currently, I am attempting to sign out the user who is already signed in within my Angular app. Here is my client service code: export class AuthClientService { public register(email: string, password: string): Observable<Object> { retu ...

JavaScript and HTML - specify the location in the html document where the JavaScript script will be displayed

I'm a beginner when it comes to JavaScript. I am trying to make sure that my HTML page remains unchanged while JavaScript text is displayed in a specific location without refreshing the entire page. To trigger a JavaScript function via a button on a ...

Ways to display or conceal dual views within a single Marionette js region

In my LayoutView, I have set up two regions: the filter region and the main region (Content Region). The main region displays a view based on the selection made in the filter region. Currently, I have a view for the main region called Current Year view. H ...

Stop the occurrence of OpenCPU javascript error pop-up notifications

I'm currently experiencing an error related to CORs during a test deployment of OpenCPU. While I may create a separate question for this issue in the future, for now, I am wondering if it is possible for the deployment to fail without alerting the end ...

Retrieving the user's Windows username with JavaScript

Is it possible to retrieve the Windows user name solely in Internet Explorer using the code below? function GetUserName() { var wshell = new ActiveXObject("WScript.Shell"); alert(wshell.ExpandEnvironmentStrings("%USERNAME%")); } What methods ...

Update information with a fresh GET call - React Dropdown

I have implemented a Dropdown Menu using MUI that allows users to select a specific day value. I would like the menu to trigger a new GET request with the updated parameter whenever the selection changes. However, I am unsure how to achieve this since it u ...

Next.js: How to retrieve route parameter within getServerSideProps

I need to retrieve data from my Supabase table using the ID provided in the URL slug, for example localhost:3000/book/1, and then display information about that specific book on a page built with Next.js. Table https://i.stack.imgur.com/t5z7d.png book/[ ...

Leveraging webpack2 for code splitting with the CommonsChunkPlugin

I encountered an issue while using code splitting and the CommonsChunkPlugin. My previous experience with require.js involved files being automatically cached. Additionally, I have configured my webpack with libraryTarget: 'amd'. When looking at ...

When utilizing Vue components, the issue of "setattr" arises when trying to assign

Having recently started using Vue.js, I encountered an issue while trying to implement components. Interestingly, the code worked perfectly fine before implementing components. I'm facing an error that is proving to be quite challenging to understand ...

How can you trigger a link click event when clicking anywhere on the page using Jquery?

Here's the code I'm working with: <a href="http://google.com" target="_blank">Open in new tab </a> I am trying to make it so that when a user clicks anywhere on the website, the link above will be automatically clicked and a new tab ...