#Problem with next-auth/react using POST requests

3 messages · Page 1 of 1 (latest)

nocturne mirage
#
/**
 * Handles the request to authorize a user's presence in a chat channel.
 *
 * @param {NextApiRequest} req - The Next.js API request object.
 * @param {NextApiResponse} res - The Next.js API response object.
 * @return {Promise<void>} - A promise that resolves with the authorized response.
 *
 * @throws {Error} - If there is an error while authorizing the user's presence.
 */
export default async function handler(req: NextApiRequest, res: NextApiResponse): Promise<void> {
    if (req.method !== "POST")
        return res.status(405).json({ error: 'Method Not Allowed' });

    const session = await getSession({ req });

    if (!session)
        return res.status(401).json({ error: 'Not authenticated' });
    if (!hasPermission(session.profile, CHAT_PERMISSION.JOIN_PRESENCE))
        return res.status(403).json({ error: 'Insufficient permissions' });

    const { socket_id, channel_name } = req.body;
    const presenceData = {
        user_id: session.user.id,
        user_info: {
            ...session.user,
            ...session.profile
        }
    };

    try {
        const auth = pusherServer.authorizeChannel(socket_id, channel_name, presenceData);
        res.status(200).json({ status: true, auth });
    } catch (error) {
        console.error(error)
        res.status(500).json({ status: false, error: 'Internal Server Error' })
    }
};

I recently started to do a project and I'm encountering a huge problem using POST request and retrieving sessions, but otherwise the GET method, there is no problem, the sessions is retrieved successfully

This part is problematic:

const session = await getSession({ req });

if (!session)
     return res.status(401).json({ error: 'Not authenticated' });

I thought that it might be due to req.body overwriting something, but honestly I'm uncertain of what it could be.

There is the details about versions:

NodeJS: v18.18.0
NextJS: 14.1.2
NextAuth: 4.24.7
OS: Win 11/Docker (node:18-bookworm)

I'm using the path /pages/api for all route handler

Does I have to migrate to NextJS v15 ? if there was already a patch about it? or could it be NextAuth itself?

stark atlasBOT
#

🔎 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)

nocturne mirage
#

Okay, I found out that await getSession({ req }) was not the best solution, but using await getServerSession(req, res, authOptions); works perfectly