Next-auth: Getting session through API

Created on 3 Jun 2020  路  4Comments  路  Source: nextauthjs/next-auth

Hi!
Great package!

One thing that I couldn't find how to do is fetch the session in a api route (/pages/api/**/*.js).

I want to check if the user is authenticated in the least, and set extra attributes at most.

I looked through the source but couldn't find anything that would let me do this.

Can you give me any tips on how to do this?

Thanks!

question

All 4 comments

Hey, so you can use the NextAuth.session() method from an API route to do this!

The example for session() should work in a route as well:
https://next-auth.js.org/getting-started/client#usesession

You just need to pass session() the req object.

e.g. session({ req }) and you should get back a session (or null, if not signed in).

We should include an example of this in the docs.

Note: This method is read only, but a server side only method for JWT tokens (which will be read + write) is planned, but not captured as an item on the road map yet.

Awesome!

I'll try that tomorrow and, when successful, add a PR with an example

@TwoAbove Thanks for this! Closing off as is merged in now.

I've updated it a bit to try also answering a related question in #206

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MelMacaluso picture MelMacaluso  路  3Comments

bscaspar picture bscaspar  路  3Comments

Xetera picture Xetera  路  3Comments

eatrocks picture eatrocks  路  3Comments

SharadKumar picture SharadKumar  路  3Comments