Next.js Discord

Discord Forum

How get the id of the connected user | Next Auth

Unanswered
LuCrypto posted this in #help-forum
Open in Discord
Hey everyone

I use Next Auth for authentification and i want create list
But create list is only for connected users

When i get the session with getServerSession, i only have expires, name, email and image but not the user ID

How can i get my user ID ?
I have to tell with email to my database ?

My code
import type { NextApiRequest, NextApiResponse } from 'next';
import { createListWhaleService } from '../../services/listWhale/listWhaleService';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const session = await getServerSession(req, res, authOptions)

  // Protect the route
  if (!session) {
    res.status(401).json({ error: 'Unauthorized' });
    return;
  }

  // Get the user id with the session
  const userId = 1;

  if (req.method === 'POST') {
    const { nameListWhale } = req.body;
    if (!nameListWhale) {
      res.status(400).json({ error: 'Missing required fields' });
      return;
    }

    // Return the new list
    const resultListWhales = await createListWhaleService(nameListWhale, userId);

    if (resultListWhales) {
      if (resultListWhales === 'List already exist') {
        res.status(400).json({ error: 'List name already exist' });
        return;
      }
      res.status(200).json({ data: resultListWhales });
    } else {
      res.status(500).json({ data: '', error: 'Internal server error' });
    }
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}


Thanks for your time

0 Replies