Session Invalidation - SuperTokens Docs

Session Invalidation

Learn how to handle session expiry, implement sign out, and revoke sessions across different programming languages and frameworks.

Overview

You can invalidate a session in SuperTokens in different ways. The main recommendation is to use the signOut function from the frontend SDK. Besides that you can also revoke sessions manually, through the backend SDKs. This guide shows you how to implement each of these.

Before you start


User sign out

The frontend SDK exposes a signOut function that revokes the session for the user. You need to add your own UI element for this since the library does not expose any components. The signOut function calls the sign out API exposed by the session recipe on the backend and revokes the current session. It does not revoke the user’s other sessions. Use the explicit all-session API shown below when that is the intended behavior. If you call the signOut function whilst the access token has expired, but the refresh token still exists, the SDKs automatically perform a session refresh before revoking the session.

UI type

Pre-built UIDrop-in components that handle the flows for you.

Frontend framework

React

import React from "react";
import { signOut } from "supertokens-auth-react/recipe/session";

function NavBar() {
  async function onLogout() {
    await signOut();
    window.location.href = "/auth"; // or redirect to wherever the login page is
  }
  return (
    <ul>
      <li>Home</li>
      <li onClick={onLogout}>Logout</li>
    </ul>
  );
}

Angular

import Session from "supertokens-web-js/recipe/session";

async function logout() {
  await Session.signOut();
  window.location.href = "/auth"; // or redirect to wherever the login page is
}

Platform

Installation method

import Session from "supertokens-web-js/recipe/session";

async function logout() {
  await Session.signOut();
  window.location.href = "/auth"; // or redirect to wherever the login page is
}

Script tag

async function logout() {
  await supertokensSession.signOut();
  window.location.href = "/auth"; // or redirect to wherever the login page is
}

ReactNative

import SuperTokens from "supertokens-react-native";

async function logout() {
  await SuperTokens.signOut();
  // navigate to the login screen..
}

Android

import android.app.Application;
import com.supertokens.session.SuperTokens;

class MainApplication: Application() {
    fun logout() {
        SuperTokens.signOut(this);
        // navigate to the login screen..
    }
}

iOS

import UIKit;
import SuperTokensIOS;

fileprivate class ViewController: UIViewController {
  func signOut() {
    SuperTokens.signOut(completionHandler: {
        error in

if error != nil {
            // handle error
        } else {
            // Signed out successfully
        }
    });
  }
}

Flutter

import 'package:supertokens_flutter/supertokens.dart';

Future<void> signOut() async {
    await SuperTokens.signOut(
      completionHandler: (error) => {
        // Handle error if any
      }
    );
}

Expose a backend sign out method

If you do not want to use the frontend function you can expose a backend sign out method.

Node.js

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("/someapi", verifySession(), async (req: SessionRequest, res) => {
  // This will delete the session from the db and from the frontend (cookies)
  await req.session!.revokeSession();

res.send("Success! User session revoked");
});

Hapi

import Hapi from "@hapi/hapi";
import { verifySession } from "supertokens-node/recipe/session/framework/hapi";
import { SessionRequest } from "supertokens-node/framework/hapi";

let server = Hapi.server({ port: 8000 });

server.route({
  path: "/someapi",
  method: "post",
  options: {
    pre: [
      {
        method: verifySession(),
      },
    ],
  },
  handler: async (req: SessionRequest, res) => {
    // This will delete the session from the db and from the frontend (cookies)
    await req.session!.revokeSession();
    return res.response("Success! User session revoked").code(200);
  },
});

Fastify

import Fastify from "fastify";
import { verifySession } from "supertokens-node/recipe/session/framework/fastify";
import { SessionRequest } from "supertokens-node/framework/fastify";

let fastify = Fastify();

fastify.post(
  "/someapi",
  {
    preHandler: verifySession(),
  },
  async (req: SessionRequest, res) => {
    // This will delete the session from the db and from the frontend (cookies)
    await req.session!.revokeSession();

res.send("Success! User session revoked");
  },
);

Other Languages

Direct session invalidation

To invalidate a session without relying on the intervention of a user you can create your own custom methods using the backend SDKs.

Revoke a specific session

Node.js

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

async function revokeSession(sessionHandle: string) {
  let revoked = await Session.revokeSession(sessionHandle);
}

Go

import(
    "net/http"
    "github.com/supertokens/supertokens-golang/recipe/session"
)

func main() {
  sessionHandle := "someSessionHandle"
  revoked, err := session.RevokeSession(sessionHandle)
  if err != nil {
    // TODO: Handle error
    return
  }

if revoked {
    // session was revoked
  } else {
    // session was not found
  }
}

Revoke all sessions for a user

Node.js

import express from "express";
import Session from "supertokens-node/recipe/session";

let app = express();

app.use("/revoke-all-user-sessions", async (req, res) => {
  let userId = req.body.userId;
  await Session.revokeAllSessionsForUser(userId);

res.send("Success! All user sessions have been revoked");
});

Go

import(
    "fmt"
    "github.com/supertokens/supertokens-golang/recipe/session"
)

func main() {
    tenantId := "public"
    revokedSessionHandles, err := session.RevokeAllSessionsForUser("userId", &tenantId)
    if err != nil {
        // TODO: Handle error
        return
    }

// revokedSessionHandles is an array of revoked session handles.
    fmt.Println(revokedSessionHandles)
}

See also Access session data Security Access token blacklisting Post login redirect Session migration