Skip to main content

Backend Integration

Supported frameworks#

1) Install#

npm i -s supertokens-node

2) Initialise SuperTokens#

Add the code below to your server's init file.

import supertokens from "supertokens-node";import Session from "supertokens-node/recipe/session";
supertokens.init({    framework: "express",    supertokens: {        connectionURI: "",        apiKey: "",    },    appInfo: {        // learn more about this on https://supertokens.com/docs/session/appinfo        appName: "<YOUR_APP_NAME>",        apiDomain: "<YOUR_API_DOMAIN>",        websiteDomain: "<YOUR_WEBSITE_DOMAIN>",        apiBasePath: "/auth",        websiteBasePath: "/auth"    },    recipeList: [        Session.init()    ]});

3) Add the SuperTokens APIs & CORS setup#

important
  • Add the middleware BEFORE all your routes.
  • Add the cors middleware BEFORE the SuperTokens middleware as shown below.
import express from "express";import cors from "cors";import supertokens from "supertokens-node";import { middleware } from "supertokens-node/framework/express";
let app = express();
app.use(cors({    origin: "<YOUR_WEBSITE_DOMAIN>",    allowedHeaders: ["content-type", ...supertokens.getAllCORSHeaders()],    credentials: true,}));
// IMPORTANT: CORS should be before the below line.app.use(middleware());
// ...your API routes

This middleware adds a few APIs (see all the APIs here):

  • POST /auth/session/refresh: It is used to get a new refresh and access token in case the older one expires.
  • POST /auth/signout: It is used sign out the currently logged in user.

4) Add the SuperTokens error handler#

import express, { Request, Response, NextFunction } from "express";import { errorHandler } from "supertokens-node/framework/express";
let app = express();
// ...your API routes
// Add this AFTER all your routesapp.use(errorHandler())
// your own error handlerapp.use((err: unknown, req: Request, res: Response, next: NextFunction) => { /* ... */ });

5) Add session verification to your API#

For your APIs that require a user to be logged in, use the verifySession middleware:

import express from "express";import { verifySession } from "supertokens-node/recipe/session/framework/express";import { SessionRequest } from "supertokens-node/framework/express";
let app = express();
app.post("/like-comment", verifySession(), (req: SessionRequest, res) => {    let userId = req.session!.getUserId();    //....});

6) Setup the SuperTokens core#

Are you using https://try.supertokens.com as the connection URI in the init function?
YesNo