Skip to main content

4. Session verification / Building your APIs

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

1) Create a new file netlify/functions/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.

let supertokens = require("supertokens-node");let { getBackendConfig } = require("../../config/supertokensConfig");

3) Use session verification with your API handler#

We use the verifySession() middleware to verify a session.

let supertokens = require("supertokens-node");let { verifySession } = require("supertokens-node/recipe/session/framework/awsLambda");let middy = require("@middy/core");let cors = require("@middy/http-cors");let { getBackendConfig } = require("../../config/supertokensConfig");
const handler = async (event, _) => {    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;});