Skip to main content

Backend Setup

Let's got through the changes required so that your backend can expose the SuperTokens authentication features.

1. Install the SDK#

Run the following command in your terminal to install the package.

npm i -s supertokens-node

2. Initialize the SDK#

You will have to intialize the Backend SDK alongside the code that starts your server. The init call will include configuration details for your app, how the backend will connect to the SuperTokens Core, as well as the Recipes that will be used in your setup.

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

import supertokens from "supertokens-node";
import Session from "supertokens-node/recipe/session";
import ThirdParty from "supertokens-node/recipe/thirdparty";

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: [
ThirdParty.init({/*TODO: See next step*/}),
Session.init() // initializes session features
]
});

3. Add the Authentication Providers#

Populate the providers array with the third party authentication providers that you want.

import SuperTokens from "supertokens-node";
import ThirdParty from "supertokens-node/recipe/thirdparty";

SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "...",
},
recipeList: [
ThirdParty.init({
signInAndUpFeature: {
// We have provided you with development keys which you can use for testing.
// IMPORTANT: Please replace them with your own OAuth keys for production use.
providers: [{
config: {
thirdPartyId: "google",
clients: [{
clientId: "1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com",
clientSecret: "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"
}]
}
}, {
config: {
thirdPartyId: "github",
clients: [{
clientId: "467101b197249757c71f",
clientSecret: "e97051221f4b6426e8fe8d51486396703012f5bd"
}]
}
}, {
config: {
thirdPartyId: "apple",
clients: [{
clientId: "4398792-io.supertokens.example.service",
additionalConfig: {
keyId: "7M48Y4RYDL",
privateKey:
"-----BEGIN PRIVATE KEY-----\nMIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgu8gXs+XYkqXD6Ala9Sf/iJXzhbwcoG5dMh1OonpdJUmgCgYIKoZIzj0DAQehRANCAASfrvlFbFCYqn3I2zeknYXLwtH30JuOKestDbSfZYxZNMqhF/OzdZFTV0zc5u5s3eN+oCWbnvl0hM+9IW0UlkdA\n-----END PRIVATE KEY-----",
teamId: "YWQCXGJRJL",
}
}]
}
}],
}
}),
// ...
]
});

When you want to generate your own keys, please refer to the corresponding documentation to get your client ids and client secrets for each of the below providers:

Google
  • Generate your client ID and secret by following the docs here
  • Set the authorisation callback URL to <YOUR_WEBSITE_DOMAIN>/auth/callback/google
Github
  • Generate your client ID and secret by following the docs here
  • Set the authorisation callback URL to <YOUR_WEBSITE_DOMAIN>/auth/callback/github
Apple
  • Generate your client ID and secret by following this article
  • Set the authorisation callback URL to <YOUR_API_DOMAIN>/auth/callback/apple. Note that Apple doesn't allow localhost in the URL. So if you are in dev mode, you can use the dev keys we have provided above.
important

You can find the list of built in providers here. To add a provider that is not listed, you can follow our guide on setting up custom providers.

4. Add the SuperTokens APIs and Configure CORS#

Now that the SDK is initialized you need to expose the endpoints that will be used by the frontend SDKs. Besides this, your server's CORS, Cross-Origin Resource Sharing, settings should be updated to allow the use of the authentication headers required by SuperTokens.

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

You can review all the endpoints that are added through the use of SuperTokens by visiting the API Specs.

5. Add the SuperTokens Error Handler#

Depending on the language and framework that you are using, you might need to add a custom error handler to your server. The handler will catch all the authentication related errors and return proper HTTP responses that can be parsed by the frontend SDKs.

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 routes
app.use(errorHandler())

// your own error handler
app.use((err: unknown, req: Request, res: Response, next: NextFunction) => { /* ... */ });

6. Secure Application Routes#

Now that your server can authenticate users, the final step that you need to take care of is to prevent unauthorized access to certain parts of the application.

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();
//....
});

The middleware function returns a 401 to the frontend if a session doesn't exist, or if the access token has expired, in which case, our frontend SDK automatically refreshes the session.

In case of successful session verification, you get access to a session object using which you can get the user's ID, or manipulate the session information.

7. Test the Login Flow#

Now that you have configured both the frontend and the backend, you can return to the frontend login page. From here follow these steps to confirm that your setup is working properly.

  • Click on the Sign up button to create a new account.
  • After you have created the account go to Login page and fill in your credentials.
  • If you are greeted with the login screen you have completed the quickstart setup.
๐ŸŽ‰ Congratulations ๐ŸŽ‰

You've successfully integrated SuperTokens with your existing application!

Of course, there are additional things that you should add in order to provide a complete authentication experience. We will talk about those things in the next section.