Quickstart
CAUTION
This guide only applies to scenarios which involve SuperTokens Session Access Tokens.
If you are implementing either, Unified Login or Microservice Authentication, features that make use of OAuth2 Access Tokens, please check the separate page that shows you how to verify those types of tokens.
note
This is applicable for when the frontend calls an API in the /pages/api folder.
For this guide, we will assume that we want an API /api/user GET which returns the current session information.
1. Create a new file /pages/api/user.ts
2. Call the supertokens.init function
Remember that whenever we want to use any functions from the supertokens-node lib, we have to call the supertokens.init function at the top of that serverless function file.
pages/api/user.ts
importsupertokensfrom'supertokens-node'
import{ backendConfig }from'../../../config/backendConfig'
supertokens.init(backendConfig())
3. Call the verifySession session function
App Info
Adjust these values based on the application that you are trying to configure. To learn more about what each field means check the references page.This is the name of your application.
This is the URL of your app's API server.
SuperTokens will expose its APIs scoped by this base API path.
This is the URL of your website.
The path where the login UI will be rendered
pages/api/user.ts
import{ superTokensNextWrapper }from'supertokens-node/nextjs'
import{ verifySession }from'supertokens-node/recipe/session/framework/express'
importsupertokensfrom'supertokens-node'
import{ backendConfig }from'../../../config/backendConfig'
importNextCorsfrom"nextjs-cors";
supertokens.init(backendConfig())
exportdefaultasyncfunctionuser(req:any, res:any){
// NOTE: We need CORS only if we are querying the APIs from a different origin
awaitNextCors(req, res,{
methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],
origin:"<YOUR_WEBSITE_DOMAIN>",
credentials:true,
allowedHeaders:["content-type",...supertokens.getAllCORSHeaders()],
});
// we first verify the session
awaitsuperTokensNextWrapper(
async(next)=>{
returnawaitverifySession()(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(),
})
}
- If no session exists, the API will return a 401 error to the client. In this case, the code return res.json will not be executed at all.
- In case the session does exist, req.session can be used to get session information. Learn more about this object here.
