Guide on enabling external API login with Next Auth v5 in Next.js 14 using the application router

While trying to navigate the documentation for Next Auth, I found myself struggling with outdated examples and an overall lack of clarity. It appears that the documentation is still a work in progress, making it challenging to find reliable information on how to effectively implement this authentication system. Despite investing hours into watching video tutorials and reading related articles, I constantly encounter outdated information due to the rapid pace at which things change.

My attempt to adapt the authentication system from the official Next.js website tutorial resulted in errors, such as the following:

Upon checking the VSCode frontend console, I encountered errors like:

Response from API: {
  user: { id: 4, username: 'bob', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73011c171c031a42...>' },
  refresh: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
  access: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
}
[auth][error] CallbackRouteError: Read more at https://errors.authjs.dev#callbackrouteerror
[auth][cause]: TypeError: "ikm"" must be an instance of Uint8Array or a string

............

[auth][details]: {
  "provider": "credentials"
}
Authentication Error: CallbackRouteError: Read more at https://errors.authjs.dev#callbackrouteerror
    at Module.callback (webpack-internal:///(action-browser)/./node_modules/@auth/core/lib/actions/callback/index.js:437:23)

....................


type: 'CallbackRouteError',
  kind: 'error',
  [cause]: {
    err: TypeError: "ikm"" must be an instance of Uint8Array or a string

I would greatly appreciate any guidance or assistance in resolving these issues.

For context, my backend is built on Django and DRF, utilizing JWT Simple, although specifics may not be crucial. The backend creates endpoints:

127.0.0.1:8000/auth/login/
127.0.0.1:8000/auth/register/
127.0.0.1:8000/auth/refresh/token

These endpoints have been verified to function correctly using Postman. In the frontend, specifically within Next.js v14:

In the project root, I have an auth.config.ts file containing the following code:

(Code snippet provided, please refer to original text for full detail)
(Additional content omitted for brevity)

Answer №1

It was definitely a challenge, but after a few days of effort, I managed to implement it successfully. If you need assistance, I'm here to help. Make sure to adjust the code examples to fit your requirements as this is a fully functional example.

  1. To start, install the recommended packages listed below. I suggest sticking to these specific versions for smooth implementation.

https://i.sstatic.net/s4hfA.png

  1. Add an auth.ts file Place it at the project's root level.

In this file, various tasks such as managing the login process, redirecting unauthorized users, and refreshing tokens are handled. Take time to review it carefully.

// Code snippet goes here...

This is just part of our setup; make sure to follow all steps thoroughly.

  1. Include custom types.

To ensure seamless integration with our session properties, create a type folder at the root level containing the next-auth.d.ts file.

The next-auth.d.ts file handles TypeScript definitions necessary for the application.

// TypeScript declarations go here...
  1. Integrate middleware.ts file.
// Middleware logic implementation...
  1. Create a [...nextauth] folder.

Add the required route configurations within the specified path.

// Route configuration snippet...

Remember to update the tsconfig.json file accordingly.

  1. Define environment variables.
// Environment variables declaration for local and production environments...

Ensure these variables are also set in your Dockerfile if applicable.

  1. Implement sign-in functionality.

Utilize client components along with server-side logic to enable user authentication seamlessly.

// Sign-in component example...

If access token refreshment fails, prompt users to log out securely.

// Secure logout mechanism...

Additional functionalities like role-based access can be implemented using provided Higher Order Components (HOC).

// Role-based access HOC usage and implementation...

Easily enforce access restrictions based on user roles with the designated HOC.

Feel free to reach out if you encounter any issues during the setup process.

BONUS: Example of role-based access control HOC

Enhance security by restricting page access based on user roles through the implemented HOC.

// Role-based access control higher-order component usage...

Utilize the HOC to limit access to specific pages based on predefined user roles.

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 useMutation function trapped in an endless loop

I've been encountering an issue while running a query to save an entity in the database using usemutation. The saveVisa() mutation seems to be stuck in an infinite loop, creating the same element multiple times without any clear reason. import {React, ...

Steps for creating a CodeBlock in a Next.js Website blog similar to the one in the provided image

Learn how to insert a code block in Next.js. def greet(name): """ This function greets the person passed in as a parameter. """ print("Hello, " + name + ". Good morning!") Here is an example of ...

Encountering a surprise token < while processing JSON with ASP.NET MVC alongside Angular

I encountered an issue when attempting to return the Index page. The data is successfully sent from the client to the server, but upon trying to display the Index page, an error occurs. Could someone review my code and identify where the mistake lies? acc ...

What is the list of status codes that Next.js returns when performing an SSR redirect?

Currently, I am utilizing the Next redirect object in my project to perform redirects within the getServerSideProps function. I am curious about what specific status code is sent back in the response. Upon reviewing the documentation, the only hint I came ...

The data output seems to be malfunctioning specifically in Next.js

import styles from './PopularPosts.module.scss' export async function getServerSideProps() { return { props: { content: "Some content" } } } export const PopularPosts = (props) => { return ( ...

What steps should I follow to set up a TypeScript project that incorporates JavaScript modules compiled from PureScript?

TL;DR I am looking to develop TypeScript typings for compiled PureScript modules and include them in my npm package. I am willing to manually maintain these typings, but I am struggling with the configuration needed in tsconfig.json (up and downstream) and ...

What is causing my session variables to not carry over to the other pages?

In my Authenticator class, I utilize the User datatype to authenticate users. include('User.datatype.php'); $usher = new Authenticator; $usher->checkCreds(); $usher->startSession(); Class Authenticator { protected $user; protecte ...

Is NextJS on-demand revalidation compatible with Next/link?

https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration#on-demand-revalidation According to the NextJS documentation, it appears that on-demand cache revalidation should function properly with regular <a> tags and when t ...

Verifying user identities on iOS devices

As I work on developing an HTTP API for our web application, my main focus is on creating a system that will not only cater to the needs of our upcoming iPhone app but also be adaptable for future platforms. One key aspect I am currently deliberating on is ...

The Environment variable in React Native is not functioning when utilizing TypeScript

After installing the react-native-dotenv library, I followed the instructions outlined in the TypeScript guide. I then created a .env file with the following contents: MARVEL_API = <url> MARVEL_PUBLIC_KEY = <public-key> MARVEL_PRIVATE_KEY = &l ...

API Routes - xxxx has been resolved by the API without sending back a response, potentially causing delays in request processing

While working on my frontend project, I encountered an issue with a simple API call using API routes. Whenever I try to complete the call, I face the following error which prevents my redirect from working: API resolved without sending a response for /ap ...

How can I easily implement basic password protection on a straightforward Next.js web app hosted on Vercel?

Adding a simple password validation step to a dashboard that only a select few would access. The data is not highly sensitive, but some basic protection is desired to limit unauthorized access. While not expecting targeted attacks from hackers, the goal is ...

Hold off on addressing the nested loops within a TypeScript subscription

Goal: Ensure all nested loops complete processing before returning final value. Problem: Final value returned prematurely, before completion of loop processing. In the code snippet below, I am sending paramListToComplete to a data service for creating a ...

Utilizing two imports within the map() method

I have been considering the idea of incorporating two imports within map() in my React code. This is how my code looks: {this.state.dataExample.map(item => ( <ItemsSection nameSection={item.name} /> item.dat ...

Error message: The Next.js GraphQL-Yoga server is returning a 404 error on the

I am brand new to using graphql-yoga 3 in conjunction with next js for creating APIs with GraphQL. Unfortunately, my routes at /api/graphql are returning a 404 error even though I have followed the example provided here. The default page loads fine, but I ...

iterating through the checked values in Angular 4

I need assistance in writing a loop using TypeScript to send each checked employee as a parameter to the postCouncilAbsence function. Can anyone help? component.ts: onattendanceSave(form:NgForm){ this.index = this.attendanceForm.value console.log ...

What causes error TS2339 to occur: The property 'classList' is not found on type 'never'

Currently, I am working on creating a basic component called "BackToTop" const BackToTop: React.FC = () => { const bttEl = useRef(null); function scrollHandler(): void { var bttHtmlEl: HTMLElement | null = bttEl.current; if (bttH ...

Enhance your Angular application with lazy loading and nested children components using named outlets

Let me start by explaining that the example provided below is a simplified version of my routes that are not functioning properly. I am working on an angular project, specifically a nativescript angular project, and I suspect the issue lies within Angular ...

What is the process for running a continuous stream listener in a node.js function?

I am currently working with a file called stream.ts: require('envkey') import Twitter from 'twitter-lite'; const mainFn = async () => { const client = new Twitter({ consumer_key: process.env['TWITTER_CONSUMER_KEY'], ...

Transfer all the child nodes to the parent using the spread operator or Object.assign while preventing duplicate properties from being overwritten

I'm trying to transfer all the nodes of a child node to the parent using the spread operator or Object.assign (without relying on Lodash) while avoiding overwriting existing properties. My initial thought was to simply append the childArray to the ro ...