Retrieve the information of the currently logged-in user on Discord using next-auth

Can anyone help me with extracting the banner and ID of the currently logged in user? Feel free to reach out at next@12 [email protected] I have successfully logged the profile details at the backend, but I'm facing issues pulling this information on the frontend. I'm new to next.js and encountering difficulties using next-auth with version 14. 😄

import DiscordProvider from "next-auth/providers/discord";

export const authOptions = {
  providers: [
    DiscordProvider({
      clientId: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
      authorization: { params: { scope: "identify guilds" } },
      profile(profile) {
        if (profile.avatar === null) {
          const defaultAvatarNumber = parseInt(profile.discriminator) % 5;
          profile.image_url = `https://cdn.discordapp.com/embed/avatars/${defaultAvatarNumber}.png`;
        } else {
          const format = profile.avatar.startsWith("a_") ? "gif" : "png";
          profile.image_url = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`;
        }

        return {
          id: profile.id,
          name: profile.username,
          discriminator: profile.discriminator,
          image: profile.image_url,
          banner: profile.banner,
          accentColor: profile.accentColor,
        };
      },
    }),
  ],

  callbacks: {
    async session({ session, user, token }) {
      if (session) {
        session.accessToken = token.accessToken;
        session.tokenType = token.tokenType;
        session.discordUser = token.profile;
      }

      return session;
    },
    async signIn({ user, account, profile, email, credentials }) {
      if (account.provider != "discord" && !user.id) {
        return;
      }

      return {
        user: {
          name: user.name,
          email: user.email,
          image: user.image,
          banner: profile.banner,
          accentColor: profile.accentColor,
        },
        accessToken: user.accessToken,
        expires: user.expires,
      };
    },

    async jwt({ token, account, profile }) {
      if (account) {
        token.accessToken = account.access_token;
      }

      return token;
    },
  },
  secret: process.env.NEXTAUTH_SECRET,
};

export default NextAuth(authOptions);

Answer â„–1

import NextAuth from 'next-auth'
import DiscordProvider from 'next-auth/providers/discord';

export const customAuthOptions = {
  providers: [
    DiscordProvider({
      clientId: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
      authorization: { params: { scope: "identify guilds" } },
      profile(profile) {
        let imageUrl = '';
        if (profile.avatar === null) {
          const defaultAvatarNumber = parseInt(profile.discriminator) % 5;
          imageUrl = `https://cdn.discordapp.com/embed/avatars/${defaultAvatarNumber}.png`;
        } else {
          const format = profile.avatar.startsWith("a_") ? "gif" : "png";
          imageUrl = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`;
        }

        return {
          id: profile.id,
          name: profile.username,
          discriminator: profile.discriminator,
          image: imageUrl,
          banner: profile.banner,
          accentColor: profile.accentColor,
        };
      },
    }),
  ],

  callbacks: {
    async session({ session, token }) {
      if (session.user) {
        session.user.id = token.profile.id;
        session.user.banner = token.profile.banner;
        session.user.accentColor = token.profile.accentColor;
        // Add any other user properties you need
      }
      return session;
    },

    async jwt({ token, user, profile }) {
      if (user) {
        token.profile = profile;
      }
      return token;
    },

    // Keep other callbacks as they are or modify them according to your requirements
  },
  secret: process.env.NEXTAUTH_SECRET,
};

export default NextAuth(customAuthOptions);

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

Sorting through various data inputs in one JSON file

I have a JSON file containing an array of objects: obj= [{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"t ...

What sets apart using 'self.fn.apply(self, message)' from 'self.fn(message)', and what are the advantages of using the former method?

Whenever I come across code that looks like thisnewPromise.promiseDispatch.apply(newPromise, message), I can't help but wonder why they didn't simply use newPromise.promiseDispathch(message) ...

Tips for retaining filled data after an incomplete form submission

<html> <head><script type="text/javascript"> function pa(){ var fname = document.getElementById('fname').value; var lname = document.getElementById('lname').value; var email = document. ...

What is the best way to transfer data from one worker to all the others in node.js?

Upon node boot up, I initialize an in-memory JavaScript object. This node app runs on multiple cores using the cluster module. When an HTTP request is received, it is handled by one of the worker threads which then modifies the value of the JavaScript ob ...

Loading GLTF model via XHR may take an infinite amount of time to reach full completion

I am attempting to load a GLTF model of a piano using XHR and showcase the loading progress on a webpage. The model is being loaded utilizing the Three.js library. On a local server, everything works perfectly - the loading percentage is shown accurately, ...

Retrieve information according to the currency specified

In my database, I have a table of tickets with prices listed in USD. If someone from a country outside the US wants to purchase a ticket, I'd like to display the prices in their local currency for better user experience. However, converting these pric ...

Reveal the hidden div by sliding it up from the bottom

I have a container with brown branches resembling the image, and I'm looking to hide it. When a button is clicked, I want it to reveal from the bottom to the top, almost like it's being unmasked. I've ruled out a typical bottom-up slide anim ...

It is not possible to make a call to Response.Redirect from within a static method

Hello, I am attempting to execute a webmethod using ajax from an aspx page. Essentially, I would like to redirect to another aspx page with a query string, but I need to do it through <a href> because it is part of a jQuery menu. Based on my underst ...

Unending loop detected in the React useEffect hook during testing

This code snippet is from the latest version of NextJS (13). export default function Members() { // States const [users, setUsers] = useState<MemberType[]>([]); const [loading, setLoading] = useState(false); const searchParams = useSearchPara ...

Implement a dynamic loading feature using AJAX, pushState, and Jekyll for a

In an effort to create a standard template for our studio's Jekyll sites development, I am aiming to implement page animation transitions. My plan involves loading different content from each page using AJAX and utilizing pushState to update the URL a ...

When utilizing getServerSideProps, the data is provided without triggering a re-render

Although my approach may not align with SSR, my goal is to render all products when a user visits /products. This works perfectly using a simple products.map(...). I also have a category filter set up where clicking on a checkbox routes to /products?catego ...

Despite passing JSLint, an unexpected end of input still occurred

It seems a bit absurd; despite my efforts, I'm unable to locate the syntax error. The Chrome debugger keeps indicating an "unexpected end of input" in line two. Any suggestions? $("head meta").each(function () { var content = JSON.parse(this.cont ...

The PHP script receives an empty string value passed from JavaScript

I am struggling to pass a string from my JavaScript code to my PHP code. Here is the code snippet that triggers when I hit Enter in a text input: $('#user').keypress(function(e) { if(e.which == 13) { var val = $(this).val(); ...

Conceal dynamically generated div elements created with ngIf

I am currently working on initializing this div using ngOnInit in Angular ngOnInit(): void { let optTemp = ''; for (let data of arrOption) { optTemp = optTemp + '<option>' + data.trim() + '</option> ...

Receive fresh properties in React and subsequently reset state

I need some guidance on this issue: My scenario involves a parent React component and its child. The parent component contains a table, while the child has its own controls. What I am trying to achieve is the ability to click on a cell within the parent&a ...

Expanding upon passing arguments in JavaScript

function NewModel(client, collection) { this.client = client; this.collection = collection; }; NewModel.prototype = { constructor: NewModel, connectClient: function(callback) { this.client.open(callback); }, getSpecificCollection: ...

What is the best way to access a variable within an event handler function?

Is there a way to retrieve values from the for-loop within an event handler? Consider this JSON array var items = [ { "id": "#id1", "name": "text1" }, { "id": "#id2", "name": "text2" } ]; that is passed as a parameter to the function function setHand ...

Path taken to reach the view requested by Node.js server

Snippet of Controller Code: bina: function(req, res) { var request = require('request'); request({ url: 'http://localhost:3000/bina/', method: 'GET', }, function(err, res, body) { ...

Loading JS scripts in MVC 4: A Guide

As a newcomer to MVC, I have encountered various challenges when it comes to loading my JavaScript files properly. Initially, here is the structure of my website: _Layout.cshtml (main page) Index.cshtml _MainMenu.cshtml (partial view) I include my M ...

Incorporate the value of a JQuery variable within an HTML form

When the Submit button is clicked, I am attempting to pass the value of currentDate to a REST GET service. However, there are two things that I don't understand. Is it possible to include the URL of the REST service in the action attribute of the fo ...