Configuring JWT with Next.js and NextAuth seems to pose a challenge

Setting up JWT with NextAuth has been a bit of a challenge for me. I've been scouring GitHub posts and doing research, but haven't found much help. It seems like there's an error occurring when NextAuth tries to decode the JWT payload. All I want is to get a string of numbers from Twitch upon signing in so that I can use it in an API call to Twitch.

I'm new to JWT and NextAuth, so I'm still learning!

If anyone could offer some assistance, that would be greatly appreciated!

// console errors
unhandledRejection: TypeError: Cannot read properties of undefined (reading 'next-auth.session-token')
-
error - Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
-
TypeError: getCurves is not a function
-

Check out the github repo for the entire project here.

If you're encountering any issues, feel free to refer to the nextjs error page https://i.sstatic.net/l73ZN.png.

//[...nextauth].js
import NextAuth from "next-auth"
import Providers from "next-auth/providers"

export default NextAuth({
  providers: [
    Providers.Twitch({
      clientId: process.env.TWITCH_CLIENT_ID,
      clientSecret: process.env.TWITCH_CLIENT_SECRET,
    }),
    Providers.Spotify({
      clientId: process.env.SPOTIFY_CLIENT_ID,
      clientSecret: process.env.SPOTIFY_CLIENT_SECRET
    }),
  ],
  secret: process.env.SECRET,

  session: {
    jwt: true,
  },

  // https://next-auth.js.org/configuration/options#jwt
  jwt: {
     secret: process.env.SECRET,
  },
  callbacks: {
     async signIn(user, account, profile) { return true },
     async session(session, user) { return session },
     async jwt(token, user, account, profile, isNewUser) { 
       token.accessToken = account.access_token;
       return token 
      }
  },
  theme: 'light',

  debug: true,
})
//test.js - trying to decode and use the data inside the web token
import { getToken } from 'next-auth/jwt'
const secret = process.env.SECRET

const test =  (req, res) => {
    const token = getToken({req, secret});
    return (
        <div>
            <a>{token.sub}</a> // Should show the users id returned from Twitch
        </div>
    )
}

export default test

Answer №1

fetchToken gives back a promise. Make sure to await for it prior to performing any operation.

const fetchData = async (req, res) => {
    const tokenData = await fetchToken({req, secret});
    return (
        <div>
            <a>{tokenData.sub}</a> // Display the user's id retrieved from Twitch
        </div>
    )
}

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

Creating a custom Chrome extension with the ability to modify the pop-up window instead of the web page

Is there a way to modify the content inside my extension's pop-up without affecting the web page being viewed by the user? Also, how can I ensure that my dropdown list functions correctly? I have two dropdown lists where selecting an option from the ...

How to transfer data from JavaScript to PHP using AJAX

After spending countless hours attempting to make this function properly, I have come to you for assistance :) I have created a PHP page that can exhibit files from a server. I am able to modify the files using an editor plugin, where the Textarea tag is ...

css displaying inconsistently on Mi Browser mobile view

Everything looks great in Chrome (mobile), but for some reason when I test it out on Mi Browser, the CSS isn't displaying correctly. I'm working with Next.js and here's a snippet from my head tag: <Head> <meta charSet="UTF-8&q ...

Arrange the parallel table columns within their own individual divs to be perfectly aligned

I have a layout with two divs stacked on top of each other, each containing a table with the same number of columns. I need to ensure that the columns in both tables are the same width and aligned properly. If a column in one table expands, I want the corr ...

Node.js application with decoupled Redis client

In my node.js app, I am utilizing Redis for user caching. Once a user logs in, their information is cached and accessed on subsequent requests to determine their access level. This allows the client to receive personalized information and views based on th ...

Adjusting the text and background hues using JavaScript results in an immediate reversal

Attempting to dynamically change the text color and background color based on user input in the textbox. While it initially works, the color changes only flash for a brief moment before reverting back. <!DOCTYPE html> <html> <head> ...

VueJS method for making an HTTP GET request

Attempting to make an http get request using Vue js. I can't seem to find any issues with the logic, although I'm not very experienced with vuejs. Continuously encountering these two errors: [Vue warn]: Error in mounted hook: "TypeError: Cann ...

Developing the search feature using Sequelize

Before diving into the question, let's take a look at the structure of the post table in my current project. module.exports = class Post extends Model { static init(sequelize) { return super.init({ title: { type: DataTypes.TE ...

Tips for determining the time and space complexity of this JavaScript code

Here are two codes utilized by my platform to establish relationships between nodes. code1 : const getNodeRelationship = (node1, node2) => { // if node1 and node2 are the same node if (node1 === node2) return null; // check direct parent ...

The success function in Ajax is constantly elusive, while the error function prevails. The data just can't seem to make it to the destination file

Thank you for your patience. This marks my initial post to the best of my recollection. The section below showcases a snippet from my calendar.js script. My current objective involves sending data obtained from a modal window in index.php over to sql.php. ...

Transitioning from using sendfile() to sendFile() function within the Express framework

Here is the code snippet I am using: router.get('/image',(req,res,next)=>{ const fileName = "path_to.jpg" res.sendfile(fileName,(err)=>{ if (err) { next(err); } else { console.log('Sent:', fileName); } ...

What are some strategies to reduce the frequency of API calls even when a webpage is reloaded?

Imagine I'm utilizing a complimentary API service that has a restriction of c calls per m minutes. My website consists of a simple HTML file with some JavaScript code like the one below: $(function () { //some code function getSomething() { ...

combining input fields for editing as a single unit instead of individually

Current Situation : At the moment, I have a form where individual records of input fields such as firstName, lastName, and email can be edited and saved without any errors. Requirement : However, I now want to be able to edit and save the firstName and ...

JavaScript does not reflect updates made to the ASP.Net session

After clicking the button, I trigger the JavaScript to retrieve the session information. However, I am encountering an issue where the value of the session is not being updated. alert('<%= Session["file"]%>'); ...

Using Django Sessions for User Authentication in React Applications

Not a coding query, but rather a general one: When using default authentication in Django (session authentication), what does the frontend (in my case it's React) require? For instance, upon logging in on the browser via the front end login button, th ...

Invoke OnSelectedIndexChanged from GridView prior to any other function execution

In my scenario, there are two GridViews available. The first GridView allows the user to select a row, based on which a corresponding list will be displayed according to the selected GridView ID. First Grid: https://i.stack.imgur.com/d0OKq.png Second Gri ...

Filtering controls within a table are not displayed in VueJS

I have been attempting to implement date filtering in my data table based on a demo I followed. Despite meeting the filter requirements, no results are being displayed which is perplexing. Below are the imports and data from the file containing the table: ...

What could be the reason for the "category empty" message appearing at the first index after clicking on the add

When I click on the add products button, why is the category name empty at the first index? 1. The text starts from index 2 of the category column. 2. When I change the value from the dropdown, it first displays the previous value in the category column an ...

Tips for creating a gradual fade-out effect on a bootstrap modal window

One issue I'm facing is with my modal dialog (#busyIndicator). It simply displays a message that reads "Please Wait". Sometimes, the operation it's tied to completes so quickly that the visual transition between showing and hiding the dialog beco ...

Stellar for occasions that don't come around often

Is it worth utilizing a Comet for events that do not require real-time updates, but can have a delay of around 1 minute? Examples could include: updates on Twitter statuses notifications on Facebook While Comet is commonly used in chat applications (suc ...