Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next auth getSession with typescript

I am using next-auth getSession in API routes like this

const mySession = await getSession({ req });

I am certain that the type of the mySession is this

type SessionType = {
  user: {
    email: string;
  };
};

When I mouseover on mySession it displays like this

const mySession: Session | null

This can be either null or type of Session.

How do I override the type with the type SessionType

I tried this

 const mySession = await getSession<SessionType>({ req });

This gives me an error

Expected 0 type arguments, but got 1.

How do I change the type of the getSession method?

like image 281
Pathum Kalhan Avatar asked May 13 '26 12:05

Pathum Kalhan


1 Answers

The reason why the method can return null is because its possible that the user/caller of your api is in fact not authenticated. So I doubt you really want to do that. Instead you could make actual use of this like the following:

const session = getSession({req});

if(!session) return res.status(401).end();


// From now on session is sure to not be null and you can do whatever you want with it

If you actually have a legitimate use-case to change the value a session can have, maybe this is useful:

You are getting the Error because getSession is not expecting you to specify a type, or put differently, getSessionis not implemented using generics.

What you can do to extend the Session is this:

  1. Extend the returned object by providing a session callback in the next auth options
  2. Override the next-auth module

Both steps are described here

like image 153
Laurenz Honauer Avatar answered May 16 '26 02:05

Laurenz Honauer