nextjs session verification
# support-questions
s
Hi, I had to integrate auth into nextjs project which I don't have much experience on. I followed all the steps in documentation and got the login and sign ups working (it was super easy, cheers). But I'm unable to get the user ID in backend API handlers. I'm seeing the NextApiRequest which is default input for back-end APIs doesn't have a session object in it. Can you please help me with an example? The documentation stops just short of using session object in backend APIs
r
hey @sahas
To get the session object in your backend API handlers, you need to use the
verifySession
middleware provided by SuperTokens. Here's an example of how you can use it in a Next.js API route:
Copy code
ts
import { superTokensNextWrapper } from 'supertokens-node/nextjs'
import { verifySession } from 'supertokens-node/recipe/session/framework/express'
import supertokens from 'supertokens-node'
import { backendConfig } from '../../../config/backendConfig'

supertokens.init(backendConfig())

export default async function user(req: any, res: any) {
    // we first verify the session
    await superTokensNextWrapper(
        async (next) => {
            return await verifySession()(req, res, next)
        },
        req, res
    )
    // if it comes here, it means that the session verification was successful


    return res.json({
        note:
            'Fetch any data from your application for authenticated user after using verifySession middleware',
        userId: req.session.getUserId(),
        sessionHandle: req.session.getHandle(),
        userDataInAccessToken: req.session.getAccessTokenPayload(),
    })
}
Docs link: https://supertokens.com/docs/emailpassword/nextjs/session-verification/in-api
supertokens-bot-test-case
3 Views