Skip to main content

5. Session verification / Building your APIs

For this guide, we will assume that we want an API /user GET which returns the current session information.

1) Create a new file user.js#

An example of this is here.

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.

import supertokens from "supertokens-node";import { getBackendConfig } from "./config";

3) Use session verification with your handler#

We use the verifySession() to verify a session.

import supertokens from "supertokens-node";import { getBackendConfig } from "../../config/supertokensConfig";import { verifySession } from "supertokens-node/recipe/session/framework/awsLambda";import { SessionEvent } from "supertokens-node/framework/awsLambda";import middy from "@middy/core";import cors from "@middy/http-cors";
const handler = async (event: SessionEvent) => {    return {        body: JSON.stringify({            sessionHandle: event.session!.getHandle(),            userId: event.session!.getUserId(),            accessTokenPayload: event.session!.getAccessTokenPayload()        })    }}
module.exports.handler = middy(verifySession(handler)).use(cors({    origin: getBackendConfig().appInfo.websiteDomain,    credentials: true,    headers: ["Content-Type", ...supertokens.getAllCORSHeaders()].join(", "),    methods: "OPTIONS,POST,GET,PUT,DELETE"})).onError(request => {    throw request.error;});

4) Configure API Gateway#

  • In your API Gateway, create a base path /user and enable Enable API Gateway CORS.
  • Create a GET method for the route and associate the lambda function we created in the above step.
  • When associating the lambda function, enable Lambda Proxy integration.
  • Enable CORS for the '/user' route with following values:
    • Add rid,fdi-version,anti-csrf to the existing Access-Control-Allow-Headers
    • Set Access-Control-Allow-Origin to '<YOUR_WEBSITE_DOMAIN>'
    • Set Access-Control-Allow-Credentials to 'true'. Don't miss out on those quotes else it won't get configured correctly.