SuperTokens

SuperTokens

  • Docs
  • Discord
  • Blog

›Quick setup

SIDEBAR_REPLACE_DOC_About this recipe

  • About this recipe

Quick setup

  • Frontend
  • Backend
  • Core

    • Self Hosted setup with Docker
    • Self Hosted setup without Docker
    • Managed Service

    Database Setup

    • MySQL
    • PostgreSQL
    • MongoDB
    • Rename database tables

Common customizations

  • Redirect To Auth Screen
  • Sign Out
  • SignUp Form

    • Prerequisite
    • Adding Extra Fields
    • Adding / Modifying field validators
    • Built in providers
    • Custom providers
    • Embed in a page
    • Terms of service & Privacy policy links
    • Show Sign Up by default

    SignIn Form

    • Prerequisite
    • Adding / Modifying field validators
    • Built in providers
    • Custom providers
    • Password managers
    • Embed in a page
  • Post sign up callbacks
  • Post sign in callbacks
  • User Roles

    • Assigning roles to users
    • Assigning roles to a session
    • Reading roles in an API
    • Reading roles in the frontend
    • Updating roles in a session

    Reset Password

    • About
    • Reset Password Email
    • Embed in a page

    Email Verification

    • About
    • Customising the email sent
    • Embed in a page

    Sessions

    • About
    • Storing session data
    • Session Verification in API
    • Revoking a session manually
    • Change session timeout
    • Checking if a session exists on the frontend
    • Get user information on the frontend
    • Fetching sessions for a user
    • Update JWT Payload
    • Update Session Data
    • Cookies and Https
    • Cookie Consent
    • Share sessions across sub domains
    • Anti CSRF
    • Same site cookies
    • JWT Signing key rotation
    • Access token blacklisting
    • Customizing Error Handling

    Styling

    • Changing Colours
    • Changing Style via CSS
    • Themes

    Changing base path

    • Website Base Path
    • API Base Path
  • User Pagination
  • Core

    • Adding API Keys
    • Tuning Performance
    • Logging

    Core CLI

    • Overview
    • Start
    • List
    • Stop
    • Uninstall

NextJS

  • About
  • 1. Configuration
  • 2. Showing Login UI
  • 3. Adding auth APIs
  • 4. Protecting a website route
  • 5. Session verification

    • 5a. Session verification in an API call
    • 5b. Session verification in getServerSideProps
  • 6. Next steps

SIDEBAR_REPLACE_DOC_Serverless Optimisation

  • Running on serverless env

SIDEBAR_REPLACE_DOC_SDKs API Reference

  • SDKs API Reference

NodeJS Setup (5 mins)

For framework specific implementation (like Next.js), please skip this section and go directly to the section with the name of your framework.

This library provides a set of functions and default APIs required for authentication.

An example implementation can be found here.

1️⃣ npm install

npm i -s supertokens-node

2️⃣ Call the init function

At the top of your index.js file, add the following code. Be sure to replace the appInfo content with your specific information (as you did for the frontend)

NodeJS
let supertokens = require("supertokens-node");
let Session = require("supertokens-node/recipe/session");
let ThirdPartyEmailPassword, {Google, Github, Facebook} = require("supertokens-node/recipe/thirdpartyemailpassword");

supertokens.init({
supertokens: {
connectionURI: "https://try.supertokens.io",
},
appInfo: {
appName: "YOUR APP NAME", // Example: "SuperTokens",
apiDomain: "YOUR API DOMAIN", // Example: "https://api.supertokens.io",
websiteDomain: "YOUR WEBSITE DOMAIN" // Example: "https://supertokens.io"
},
recipeList: [
ThirdPartyEmailPassword.init({
providers: [
Google({
clientSecret: "GOOGLE_CLIENT_SECRET",
clientId: "GOOGLE_CLIENT_ID"
}),
Github({
clientSecret: "GITHUB_CLIENT_SECRET",
clientId: "GITHUB_CLIENT_ID"
}),
Facebook({
clientSecret: "FACEBOOK_CLIENT_SECRET",
clientId: "FACEBOOK_CLIENT_ID"
})
]
}),
Session.init() // initializes session features

]
});
Please refer to the corresponding documentations to get your client ids and client secrets for each of the below providers:
- Google
- Github
- Facebook

Make sure that the above configurations for "CLIENT_SECRET" are stored in your environment variables and not directly in your javascript files for security reasons.

If you noticed, we used https://try.supertokens.io as the connectionURI above. This is a Core that we are hosting for the demo app.

You can continue to use this for as long as you like, but once you are more committed to using SuperTokens, you will need to run a Core dedicated for your app.

3️⃣ Add the SuperTokens and CORS middleware

Add the middleware BEFORE all your routes.

NodeJS
let cors = require("cors");
let supertokens = require("supertokens-node");

supertokens.init({...}) // from step 2

let app = express();

// ...other middlewares
app.use(cors({
origin: websiteUrl,
allowedHeaders: ["content-type", ...supertokens.getAllCORSHeaders()],
credentials: true,
}));

app.use(supertokens.middleware());

// ...your API routes

This middleware automatically adds a few APIs:

  • POST /auth/signinup: For signing up/signing in a user using a thirdparty provider.
  • POST /auth/signup: For signing up a user with email & password
  • POST /auth/signin: For signing in a user with email & password
  • More APIs can be found here:
    • ThirdParty APIs
    • Emailpassword APIs
    • Session APIs

/auth/ is a base path that can be changed if you want.

4️⃣ Add the SuperTokens error handler

Add the errorHandler AFTER all your routes, but BEFORE your error handler

NodeJS
// ...your API routes

app.use(supertokens.errorHandler())

// your own error handler
app.use((err, req, res, next) => {...});

5️⃣ Test if sign up is setup correctly

  • Go to the /auth route of your website
  • Try to sign up.
  • If after signing up, you are redirected to /, everything is setup correctly 😁
  • If not, don't worry, you can always ask for help via Github issues or via our Discord

6️⃣ Add session verification

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

NodeJS
let Session = require("supertokens-node/recipe/session");

app.post("/like-comment", Session.verifySession(), (req, res) => {
let userId = req.session.getUserId();
//....
});

Minimum setup completed 🎉🥳

Congratulations! You now have a fully functional login and session system!

The next steps is to setup your SuperTokens core instance.

← FrontendSelf Hosted setup with Docker →