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?
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:
Both steps are described here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With