#Next-Auth

104 messages · Page 1 of 1 (latest)

spark shell
#

Where the hell am I suppost to put nextauth and configure it?? first time ive actually tried making a good dashboard but idk how to make the login auth work!!! please help

frigid monolithBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

rough ventureBOT
# spark shell Where the hell am I suppost to put nextauth and configure it?? first time ive ac...
Please add more information to your question

Your question currently does not have sufficient information for people to be able to help. Please add more information to help us help you, for example: relevant code snippets, a reproduction repository, and/or more detailed error messages. See more info on how to ask a good question in https://discord.com/channels/752553802359505017/1138338531983491154 and #welcome message

tame bronze
#

What exactly do you need help on

#

Because just from this question content, we don’t even know where you want help

spark shell
#

i need help on placement of the nextauth file, cause if i place it in api/auth it says 404

tame bronze
#

Or read the tutorial which has one part explaining how to set up next-auth v5 beta

past magnet
#

from my experience only the beta5 works in v5 ^

tame bronze
#

Yes. If you try v5 you should use beta 5 or earlier since there is a standing bug. Actually beta 4 is better since beta 5 has a type bug as well if you use typescript

spark shell
#

where do i place nextauth.url like the .env file itself? in the app directory or root

past magnet
#

I didn't notice anything

spark shell
#

[next-auth][warn][NO_SECRET]
https://next-auth.js.org/warnings#no_secret

code:

import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { getSession } from 'next-auth/react';
import Card from "../ui/dashboard/card/card";
import CommandLogs from "../ui/dashboard/command-logs/command-logs";
import styles from "../ui/dashboard/dashboard.module.css"
import Rightbar from "../ui/dashboard/rightbar/rightbar";

export default function Dashboard({ session, ...pageProps }) {
    const router = useRouter();

    useEffect(() => {
        const checkSession = async () => {
            const sessionData = await getSession();
            if (!sessionData) {
                router.push('/login'); // Redirect to login page if not signed in
            }
        };

        checkSession();
    }, []);

    // If session is not defined yet, render loading state or something else
    if (!session) {
        return <div>Loading...</div>;
    }

    return (
        <div className={styles.wrapper}>
            <div className={styles.main}>
                <div className={styles.cards}>
                    <Card />
                    <Card />
                    <Card />
                </div>
                <CommandLogs />
            </div>
            <div className={styles.side}>
                <Rightbar />
            </div>
        </div>
    );
}

This is a list of warning output from NextAuth.js.

past magnet
#

U have misconfigured ur provider

spark shell
#

discord is my provider

#

i signed in successfully but it says no secret when i go to page

#

the code i sent is for that page

#

also, where do i put my sessionprovider so i can retrieve details of the logged in user anywhere in my app? cause i dont have a _app file

#

do@tame bronzedo u have any idea of how i can do that?

tame bronze
tame bronze
past magnet
spark shell
#

there is a secret there..

#

else it wouldnt have worked

spark shell
#

wait, do i have to use the same secret to decode?

past magnet
past magnet
spark shell
#

i am

#

in env file, do i use the same secret?

#

[next-auth][error][JWT_SESSION_ERROR]
https://next-auth.js.org/errors#jwt_session_error decryption operation failed {
message: 'decryption operation failed',
stack: 'JWEDecryptionFailed: decryption operation failed\n' +
' at gcmDecrypt (webpack-internal:///(ssr)/./node_modules/jose/dist/node/cjs/runtime/decrypt.js:67:15)\n' +
' at decrypt (webpack-internal:///(ssr)/./node_modules/jose/dist/node/cjs/runtime/decrypt.js:92:20)\n' +
' at flattenedDecrypt (webpack-internal:///(ssr)/./node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js:143:52)\n' +
' at async compactDecrypt (webpack-internal:///(ssr)/./node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js:18:23)\n' +
' at async jwtDecrypt (webpack-internal:///(ssr)/./node_modules/jose/dist/node/cjs/jwt/decrypt.js:8:23)\n' +
' at async Object.decode (webpack-internal:///(ssr)/./node_modules/next-auth/jwt/index.js:66:7)\n' +
' at async Object.session (webpack-internal:///(ssr)/./node_modules/next-auth/core/routes/session.js:43:28)\n' +
' at async AuthHandler (webpack-internal:///(ssr)/./node_modules/next-auth/core/index.js:165:27)\n' +
' at async getServerSession (webpack-internal:///(ssr)/./node_modules/next-auth/next/index.js:159:19)\n' +
' at async Dashboard (webpack-internal:///(ssr)/./app/dashboard/page.jsx:31:21)',
name: 'JWEDecryptionFailed'
}
null

this keeps happening btw

This is a list of errors output from NextAuth.js.

past magnet
#

Show full auth file

#

Maybe something else is wrong

spark shell
#
import NextAuth from 'next-auth';
import { NextAuthOptions } from 'next-auth';
import DiscordProvider from 'next-auth/providers/discord';
import { getServerSession } from "next-auth"

const options: NextAuthOptions = {
  providers: [
    DiscordProvider({
      clientId: "1166465149167751269",
      clientSecret: "REDACTED",
    }),
  ],
};

export function auth(...args: [GetServerSidePropsContext["req"], GetServerSidePropsContext["res"]] | [NextApiRequest, NextApiResponse] | []) {
    return getServerSession(...args, options)
}
const handler = NextAuth(options)
export { handler as GET, handler as POST}```
#

dashboard page to retrieve session

import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { getSession } from 'next-auth/react';
import Card from "../ui/dashboard/card/card";
import CommandLogs from "../ui/dashboard/command-logs/command-logs";
import styles from "../ui/dashboard/dashboard.module.css"
import Rightbar from "../ui/dashboard/rightbar/rightbar";
import { getServerSession } from "next-auth/next"
import { options } from "app/api/auth/[...nextauth]/route.ts"

export default async function Dashboard() {
    const session = await getServerSession(options)

    console.log(session)

    return (
        <div className={styles.wrapper}>
            <div className={styles.main}>
                <div className={styles.cards}>
                    <Card />
                    <Card />
                    <Card />
                </div>
                <CommandLogs />
            </div>
            <div className={styles.side}>
                <Rightbar />
            </div>
        </div>
    );
}
past magnet
spark shell
#

its just alot of exports

past magnet
#

I use the useSession function from the /react shit

spark shell
#

how can i integrate that

past magnet
#

Just const data = useSession()

#

U got data.status and data.session there

spark shell
#

/dashboard
⨯ node_modules\next-auth\react\index.js (119:0) @ useSession
⨯ Error: [next-auth]: useSession must be wrapped in a <SessionProvider />
at Navbar (./app/ui/dashboard/navbar/navbar.jsx:18:77)

past magnet
#

Do layout file

#

Why u don't have layout

spark shell
#

I do

#

2 seconds

spark shell
# past magnet Why u don't have layout
import { Inter } from 'next/font/google'
import './ui/globals.css'
const inter = Inter({ subsets: ['latin'] })
import { SessionProvider } from 'next-auth/react';

export const metadata = {
  title: 'new ukcc dashboard!??!',
  description: 'real',
}

export default function RootLayout({ children }) {
  return (
    <html lang="en">
    <SessionProvider session={pageProps.session}>
    <body className={inter.className}>{children}</body>
    </SessionProvider>
    </html>
  )
}```


heres my layout file as of now
#

pageprops idk how to do that stuff

past magnet
#

U dont need the session={}

spark shell
#

ok

#

[next-auth][error][JWT_SESSION_ERROR]
https://next-auth.js.org/errors#jwt_session_error decryption operation failed {
message: 'decryption operation failed',
stack: 'JWEDecryptionFailed: decryption operation failed\n' +
' at gcmDecrypt (webpack-internal:///(rsc)/./node_modules/jose/dist/node/cjs/runtime/decrypt.js:68:15)\n' +
' at decrypt (webpack-internal:///(rsc)/./node_modules/jose/dist/node/cjs/runtime/decrypt.js:91:20)\n' +
' at flattenedDecrypt (webpack-internal:///(rsc)/./node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js:137:52)\n' +
' at async compactDecrypt (webpack-internal:///(rsc)/./node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js:20:23)\n' +
' at async jwtDecrypt (webpack-internal:///(rsc)/./node_modules/jose/dist/node/cjs/jwt/decrypt.js:10:23)\n' +
' at async Object.decode (webpack-internal:///(rsc)/./node_modules/next-auth/jwt/index.js:44:25)\n' +
' at async Object.session (webpack-internal:///(rsc)/./node_modules/next-auth/core/routes/session.js:25:34)\n' +
' at async AuthHandler (webpack-internal:///(rsc)/./node_modules/next-auth/core/index.js:161:37)\n' +
' at async getServerSession (webpack-internal:///(rsc)/./node_modules/next-auth/next/index.js:126:21)\n' +
' at async Dashboard (webpack-internal:///(rsc)/./app/dashboard/page.jsx:22:21)',
name: 'JWEDecryptionFailed'
}
null
⨯ node_modules\next-auth\react\index.js (451:10) @ SessionProvider
⨯ Error: React Context is unavailable in Server Components
at stringify (<anonymous>)
null
⨯ node_modules\next-auth\react\index.js (451:10) @ SessionProvider
⨯ Error: React Context is unavailable in Server Components
at stringify (<anonymous>)
digest: "4130670165"
null

This is a list of errors output from NextAuth.js.

#

Unhandled Runtime Error
Error: React Context is unavailable in Server Components

past magnet
#

I will send u my auth config soon

spark shell
#

ok

past magnet
#

Is ur dashboard a "use client"?

#

Or no?

spark shell
#

let me see

#

no

past magnet
#

U should use await auth()

#

U import form auth config file

#
import NextAuth from "next-auth"
import Discord from "next-auth/providers/discord"
import type { NextAuthConfig } from "next-auth"

export const config = {
  session: {
    strategy: "jwt"
  },
  providers: [
    Discord({
      clientId: process.env.DISCORD_CLIENT_ID ?? "",
      clientSecret: process.env.DISCORD_CLIENT_SECRET ?? "",
      authorization: "https://discord.com/api/oauth2/authorize?scope=identify+email+guilds",
    }),
  ],
  callbacks: {
    async jwt({ token, account }) {
      if (account) {
        try {
          const response = await fetch('https://discord.com/api/users/@me/guilds', {
            headers: {
              Authorization: `Bearer ${account?.access_token}`,
            },
          });
          const guilds = await response.json();
          token.guilds = guilds.filter((guild: { owner: boolean, permissions: number }) =>
            guild.owner ||
            (guild.permissions & 0x20) === 0x20 || // ADMINISTRATOR permission
            (guild.permissions & 0x08) === 0x08 // MANAGE_GUILD permission
          );
        } catch {
          token.guilds = [];
        }
      }
      return token;
    },
    // @ts-expect-error
    async session({ session, token }) {
      // @ts-expect-error
      session.accessToken = token.accessToken;
      // @ts-expect-error
      session.user.guilds = token.guilds
      return session;
    },
  },
} satisfies NextAuthConfig

export const { handlers, auth, signIn, signOut } = NextAuth(config)
#

This is what I got

#

For server side session fetch

#

I import auth from this file

#

And do const session = await auth()

#

If no session, undefined

#

There's no status/data like on useSession

spark shell
#

⨯ node_modules\next-auth\react\index.js (451:10) @ SessionProvider
⨯ Error: React Context is unavailable in Server Components
at stringify (<anonymous>)
null
⨯ node_modules\next-auth\react\index.js (451:10) @ SessionProvider
⨯ Error: React Context is unavailable in Server Components
at stringify (<anonymous>)
digest: "20988985"
null
my only errors rn

#

its in a layout.js file

#

should it be tsx?

#
import Sidebar from "../ui/dashboard/sidebar/sidebar";
import styles from "../ui/dashboard/dashboard.module.css"
import { useSession } from 'next-auth/react';

const Layout = ({ children }) => {
    const [session, loading] = useSession();
    console.log(session)
    if (loading) {
        return <div>Loading...</div>;
    }
    return (
        <div className={styles.container}>
            <div className={styles.menu}>
            {session && <Sidebar username={session.username} />}
            </div>
            <div className={styles.content}>
                <Navbar />
                {children}
            </div>
        </div>
    )
}

export default Layout```

@past magnet can i do this?
past magnet
#

I dont think so

#

no idea tbh

spark shell
#

how can i do it

#

like extract username

past magnet
#

status can be "authenticated", "loading", "unauthenticated"

spark shell
#

isnt there any username?

past magnet
#

u need to use the data.session for that

#

data.session.user.username i believe

spark shell
#

where do i get data from

#

can you make me an small snippet please

past magnet
#

i told u

#

const data = useSession()

spark shell
#

"React Context is unavailable in Server Components"

#

wait ill try an different approach

#

app\ui\dashboard\sidebar\sidebar.jsx (54:25) @ useSession

52 | ];
53 | const Sidebar = () => {

54 | const data = useSession()
| ^
55 | console.log(data)
56 | return (
57 | <div className={styles.container}>

spark shell
#

how can i secure my endpoints, also i keep getting { data: undefined, status: 'loading', update: [Function: update] }

past magnet
#

Loading means it has auth but isn't ready yet

spark shell
#

how can i extract usernames wothout error of client component

vivid cave
#

@spark shell

#

Github Source Code: https://github.com/bwestwood11/next-auth-tutorial

Private 1 on 1 Help 👇
https://calendly.com/dabrettwestwood/30min

Join my FREE Discord to talk and network about web development! 👇
https://discord.gg/kqCyVNVZWt

In this video, I will go over Next Auth and how to set up an actual working login and register page that authenti...

▶ Play video
#

check this tutorial

#

is complete

#

it explains you everything

#

get session datra client and server side and all the stuff you need

spark shell
#

foxed it

spark shell