Next.js Discord

Discord Forum

Problem with next-auth/react using POST requests

Answered
Azawakh posted this in #help-forum
Open in Discord
AzawakhOP
/**
 * 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?
Answered by Azawakh
Okay, I found out that await getSession({ req }) was not the best solution, but using await getServerSession(req, res, authOptions); works perfectly
View full answer

1 Reply

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