#Can't found session

1 messages · Page 1 of 1 (latest)

thick parcel
#

Hey, i cloned https://github.com/emmaboecker/mod-installer and while using it when i try to save mods

It says that the session is not found

https://next-auth.js.org/errors#client_fetch_error undefined {
  error: {},
  url: 'http://141.94.37.234:3000/api/auth/session',
  message: undefined
}

I tried to got at http://141.94.37.234:3000/api/auth/session and i can see my session json with my info filed so idk why it saying that i don't find it

Here is the concerned code :

set.ts

import type {NextApiRequest, NextApiResponse} from 'next'
import clientPromise from "../../../lib/mongodb";
import {getSession} from "next-auth/react";
import {Loader, Mod, ModProfile, Server} from "../../../types/modProfile";
import {Role} from "../../../types/role";
import {makeId} from "../../../lib/makeId";

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse
) {
    if (req.method !== "POST") {
        res.status(405).send({message: "Only POST requests allowed"})
        return
    }

    const session = await getSession(res)

    if (!session) {
        res.status(401).end()
        return
    }
....
vivid prawnBOT
#

Hi @thick parcel. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

thick parcel
#

UpdateModListButton.tsx

import {Button} from "@mantine/core";
import {useModEditorContext} from "../ModEditor";
import {useRouter} from "next/router";
import {useNotifications} from "@mantine/notifications";
import {useState} from "react";

export function UpdateModListButton() {
    const modStateContext = useModEditorContext()

    const router = useRouter()

    const notifications = useNotifications()

    const [updating, setUpdating] = useState(false)

    function updateModList() {
        setUpdating(true)
        modStateContext.modProfile.id = modStateContext.modProfile.name.toLowerCase().replaceAll(/[^\w]/g, "-")
        fetch("/api/profile/set", {method: "POST", body: JSON.stringify(modStateContext.modProfile)}).then(response => {
            if (response.status === 200) {
                if (modStateContext.modProfile._id !== modStateContext.modProfile.oldkey || router.route.startsWith("/new")) {
                    response.json().then(value => {
                        router.replace(`/edit/${value._id}`).then(() => {
                            modStateContext.setModProfile(value)
                        })
                    })
                }
                notifications.showNotification({
                    color: "green",
                    message: `Your Mod-List ${modStateContext.modProfile.name} was updated`
                })
            } else if (response.status === 406) {
                notifications.showNotification({
                    color: "red",
                    message: `You haven't filled out all required values yet`
                })
            } else {
                notifications.showNotification({
                    color: "red",
                    message: `There was an error. Got response code: ${response.status}`
                })
            }
            setUpdating(false)
        })
    }
vivid prawnBOT
#

The issue you're experiencing seems to be related to the getSession function not being able to retrieve the session data. This could be due to a variety of reasons, such as the session not being properly set or the session data not being accessible in the context where getSession is being called.

In your code, you're calling getSession with res as an argument, which is the response object. However, getSession should be called with the request object (req) as an argument. This is because the session data is typically stored in cookies, which are part of the request headers.

Here's how you should call getSession:

const session = await getSession({ req });

This is demonstrated in the examples from the knowledge sources:

Please try updating your code accordingly and see if it resolves the issue.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@thick parcel kapa.ai is still learning and improving, please let us know how it did by reacting below

thick parcel
vivid prawnBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The error message you're seeing is from NextAuth.js, and it's indicating that there was an error when trying to fetch the session data from the /api/auth/session endpoint. The error object is empty, which makes it difficult to determine the exact cause of the error.

However, one common reason for this error is that the server where your Next.js application is running cannot reach the specified URL. This could be due to network issues, the server being down, or the URL being incorrect.

Here are a few things you can check:

  1. Server Status: Ensure that your server at 'http://141.94.37.234:3000' is up and running.

  2. URL Correctness: Verify that the URL 'http://141.94.37.234:3000/api/auth/session' is correct. You can do this by manually visiting the URL in your web browser.

  3. Network Issues: If your server is running in a Docker container or a different network, it might not be able to reach the URL due to network restrictions. You might need to adjust your network settings to allow the server to reach the URL.

  4. NextAuth.js Configuration: Check your NextAuth.js configuration to ensure it's correctly set up. You can refer to the NextAuth.js documentation (https://next-auth.js.org/configuration/options) for more details.

If you're still having issues after checking these, you might want to consider asking for help in the Next.js GitHub Discussions (https://github.com/nextauthjs/next-auth/discussions) or the Next.js Discord server (https://discord.com/invite/nextjs).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@thick parcel kapa.ai is still learning and improving, please let us know how it did by reacting below

thick parcel
#

everything is working and up

hrere is my nextauth.js config

import NextAuth from "next-auth"
import DiscordProvider from "next-auth/providers/discord";
import {MongoDBAdapter} from "@next-auth/mongodb-adapter";
import clientPromise from "../../../lib/mongodb";
import {Role} from "../../../types/role";
import {ObjectId} from "bson";

export default NextAuth({
adapter: MongoDBAdapter(clientPromise()),
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID!!,
clientSecret: process.env.DISCORD_CLIENT_SECRET!!
})
],
callbacks: {
async session({session, user}) {
console.log('Session:', session);
const client = await clientPromise()
const userCollection = client.db().collection("users")
const accountCollection = client.db().collection("accounts")
const userDoc = await userCollection.findOne({_id: new ObjectId(user.id)}) ?? {role: Role.DEFAULT}
const accountDoc = await accountCollection.findOne({userId: new ObjectId(user.id)})
session.user.id = accountDoc?.providerAccountId
session.user.username = user.name as string
session.user.image = user.image as string
session.user.role = userDoc.role
return session
}
},
events: {
async createUser({user}) {
const client = await clientPromise()
const collection = client.db().collection("users")

        collection.updateOne(
            {_id: new ObjectId(user.id)},
            {
                $set: {
                    role: Role.DEFAULT
                }
            }
        ).then(async (r) => {
            if (r.modifiedCount === 0 || r.modifiedCount > 1) {
                console.error("failed to create role value")
            }
        }).catch(reason => {
            console.log(`error whi...

@vivid prawn

vivid prawnBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Your NextAuth.js configuration seems to be correctly set up for using Discord as an authentication provider and MongoDB as the session store. The error you're encountering is likely not due to your NextAuth.js configuration.

The error message you're seeing is a client fetch error from NextAuth.js, which typically means that there was an issue when the client (your Next.js application) tried to fetch the session data from the /api/auth/session endpoint.

Given that your server is up and running and the URL is correct, the issue might be related to how the session data is being fetched on the client side.

Here are a few things you can check:

  1. Client-Side Fetching: Ensure that you're correctly fetching the session data on the client side. You should be using the useSession hook from next-auth/react in your components to access the session data.

  2. Session Callback: In your session callback, you're modifying the session object by adding new properties like id, username, image, and role. Ensure that these properties are being correctly set and that the values are not undefined.

  3. Error Handling: Add error handling in your session callback and createUser event to catch and log any errors that might occur when interacting with your MongoDB database. This can help you identify if the issue is related to your database operations.

If you're still having issues after checking these, you might want to consider asking for help in the NextAuth.js GitHub Discussions (https://github.com/nextauthjs/next-auth/discussions) or the Next.js Discord server (https://discord.com/invite/nextjs).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@thick parcel kapa.ai is still learning and improving, please let us know how it did by reacting below

thick parcel
#

{
"user": {
"name": "billetde20",
"email": "zaidoroxlevrai@gmail.com",
"image": "https://cdn.discordapp.com/avatars/1148991156571611197/d3d7e573bfbd1ba4742384766785c9c9.png",
"id": "1148991156571611197",
"username": "billetde20",
"role": 0
},
"expires": "2024-04-22T15:32:34.501Z"
}

in the session url i get these so it works fine and send me edited code with error handling in session callback and createUsser event so i can catch and log any errors{
"user": {
"name": "billetde20",
"email": "zaidoroxlevrai@gmail.com",
"image": "https://cdn.discordapp.com/avatars/1148991156571611197/d3d7e573bfbd1ba4742384766785c9c9.png",
"id": "1148991156571611197",
"username": "billetde20",
"role": 0
},
"expires": "2024-04-22T15:32:34.501Z"
}

in the session url i get these so it works fine and send me edited code with error handling in session callback and createUsser event so i can catch and log any errors
@vivid prawn

vivid prawnBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Sure, I can help you add error handling to your session callback and createUser event. Here's how you can modify your code:

export default NextAuth({
    adapter: MongoDBAdapter(clientPromise()),
    providers: [
        DiscordProvider({
            clientId: process.env.DISCORD_CLIENT_ID!!,
            clientSecret: process.env.DISCORD_CLIENT_SECRET!!
        })
    ],
    callbacks: {
        async session({session, user}) {
            try {
                const client = await clientPromise()
                const userCollection = client.db().collection("users")
                const accountCollection = client.db().collection("accounts")
                const userDoc = await userCollection.findOne({_id: new ObjectId(user.id)}) ?? {role: Role.DEFAULT}
                const accountDoc = await accountCollection.findOne({userId: new ObjectId(user.id)})
                session.user.id = accountDoc?.providerAccountId
                session.user.username = user.name as string
                session.user.image = user.image as string
                session.user.role = userDoc.role
                return session
            } catch (error) {
                console.error('Error in session callback:', error)
                throw error // This will return a 500 error to the client
            }
        }
    },
    events: {
        async createUser({user}) {
            try {
                const client = await clientPromise()
                const collection = client.db().collection("users")
#

await collection.updateOne(
{_id: new ObjectId(user.id)},
{
$set: {
role: Role.DEFAULT
}
}
)
} catch (error) {
console.error('Error in createUser event:', error)
throw error // This will return a 500 error to the client
}
}
},
})


In this code, I've wrapped the contents of the `session` callback and `createUser` event in a try-catch block. If an error occurs when interacting with the database, it will be caught and logged to the console. The error is then re-thrown, which will cause NextAuth.js to return a 500 error to the client.

Please replace your existing NextAuth.js configuration with this code and see if it helps you identify the issue.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------