How to get userId on api Endpoints while using next-auth #536
-
Please refer to the documentation, the example project and existing issues before creating a new issue. Your question Documentation feedback
|
Beta Was this translation helpful? Give feedback.
Replies: 27 comments 35 replies
-
Is this it? |
Beta Was this translation helpful? Give feedback.
-
May be related to #535. |
Beta Was this translation helpful? Give feedback.
-
oh yeah. thats what I did as well, forgot that part. in [...nextauth].js:
|
Beta Was this translation helpful? Give feedback.
-
@yuyaoiwa-houzz -- still getting error [next-auth][error][SESSION_ERROR] [ |
Beta Was this translation helpful? Give feedback.
-
@nyedidikeke I'm getting user as undefined |
Beta Was this translation helpful? Give feedback.
-
@youngnishant can you please post the relevant code? |
Beta Was this translation helpful? Give feedback.
-
callbacks: { |
Beta Was this translation helpful? Give feedback.
-
Maybe your DB isnt configured correctly? |
Beta Was this translation helpful? Give feedback.
-
@yuyao17 actually I'm using mongodb and checked it, it's working properly |
Beta Was this translation helpful? Give feedback.
-
@youngnishant are you using JWT? I had a similar issue using mongodb and followed the docs at https://next-auth.js.org/configuration/callbacks which states...
I did so accordingly and was able to get a user id into my session object by using the below 2 callbacks:
jwt: async (token, user, account, profile, isNewUser) => {
if (user) {
token.uid = user.id;
}
return Promise.resolve(token);
}
session: async (session, user) => {
session.user.uid = user.uid;
return Promise.resolve(session);
} I am then able to access |
Beta Was this translation helpful? Give feedback.
-
@shufflemattdev actually I'm not using JWT ? |
Beta Was this translation helpful? Give feedback.
-
I'm glad that you tried to help 😊😄 |
Beta Was this translation helpful? Give feedback.
-
Hey @youngnishant I am facing the exact same issue, can't fin the _id anywhere. Did you end up fixing it? |
Beta Was this translation helpful? Give feedback.
-
Note: If I disable |
Beta Was this translation helpful? Give feedback.
-
@benoror I've implemented my own jwt authentication by taking proper security measures ✌️ |
Beta Was this translation helpful? Give feedback.
-
Try this: // pages/api/auth/[...nextauth].js callbacks: { const session = await getSession({ req }); |
Beta Was this translation helpful? Give feedback.
-
If you're using TypeScript then you'll also want to augment the default next-auth types by adding a file import { DefaultUser } from "next-auth";
declare module "next-auth" {
/**
* Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
*/
interface Session {
user: DefaultUser & {
id: string;
};
}
} |
Beta Was this translation helpful? Give feedback.
-
I'm using [EDIT] See my updated, simplified solution: #536 (reply in thread)
|
Beta Was this translation helpful? Give feedback.
-
You are my hero, @ruohola. THX a lot!!! Your solution was working for me. |
Beta Was this translation helpful? Give feedback.
-
Hi i'm trying out CredentialsProvider and when i'm trying to return the id it doesn't show up. the only things show up is (name,email,image) is it possible to get the _id from mongo db?
|
Beta Was this translation helpful? Give feedback.
-
Why isn't this in the example app? Auth is pretty useless if you don't remember the user id of the person who logged in, right? Do you have a solution for non-JWT sessions? Is that not something the database adapters (e.g. prisma) handle automatically? |
Beta Was this translation helpful? Give feedback.
-
Here's what I came up with for those who don't want to use JWT. // pages/api/auth/[...nextauth].ts
import NextAuth from "next-auth"
import TwitterProvider from "next-auth/providers/twitter"
import prisma from "@/lib/prisma"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
export default NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
TwitterProvider({
clientId: process.env.TWITTER_ID,
clientSecret: process.env.TWITTER_SECRET,
version: "2.0",
}),
],
session: {strategy: "database"},
}) // pages/api/test.ts
import prisma from "@/lib/prisma"
import { getCookie } from 'cookies-next';
export default async function handler(req, res) {
const token = getCookie('next-auth.session-token', {req, res}) as string
const session = await prisma.session.findUnique({where: {sessionToken: token}})
res.status(200).json(session)
} // lib/prisma.ts
import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()
export default prisma This uses the // pages/api/test.ts
import prisma from "@/lib/prisma"
import cookie from 'cookie';
export default async function handler(req, res) {
const cookies = cookie.parse(req.headers.cookie || '')
const token = cookies['next-auth.session-token']
const session = await prisma.session.findUnique({where: {sessionToken: token}})
res.status(200).json(session)
} |
Beta Was this translation helpful? Give feedback.
-
This code worked for me, now I'm on next-auth version ^4.6.1. Then the object user is completely undefined in the jwt callback and session. I logged the check and the user id exists again inside the token's sub. Totally fine with me!
|
Beta Was this translation helpful? Give feedback.
-
@balazsorban44 @nickretallack @leephan2k1 I wanted not just the userId, but also the additional fields I had added to my user model and ended up with, what seems to me at least, an even simpler solution:
|
Beta Was this translation helpful? Give feedback.
-
If anyone is wondering how to do this on Next.js 13 using NextAuth 4.22.1 using TypeScript, where I am returning data from the database about the user, including ID and roles, here ya go: First, you have to make some custom types inside your types folder (you may need to edit your tsconfig.ts if you're not defining typeRoots by adding):
then, create a file called /next-auth.d.ts mines inside '/src/app/types' (or whatever folder your types are in):
Then you need this inside [...nextauth].js:
then, fire away on the session callback:
|
Beta Was this translation helpful? Give feedback.
-
Fix: Convert your server side session to client and don't pass session to SessionProvider. Somehow your custom session is overwriting by this session object. If there is a good solution I also would like to know. PS: I tried types trick. It only solved type checking.
|
Beta Was this translation helpful? Give feedback.
-
I have the same problem (sort of). I am able to get userId using useSession() hook, but getServerSession() doesn't include userId. |
Beta Was this translation helpful? Give feedback.
I'm using
next-auth
4.0.5
. Here's how I solved it (mostly combining advice from this thread):[EDIT] See my updated, simplified solution: #536 (reply in thread)
src/pages/api/auth/[...nextAuth].ts
:types.d.ts
(file in project root):