SuperTokens Website Frontend SDK

20.1.6 · active · verified Wed Apr 22

SuperTokens Website Frontend SDK (npm package `supertokens-website`) is a JavaScript library designed to manage user authentication and session lifecycles for web applications. Currently at version 20.1.6, this SDK facilitates seamless integration with SuperTokens backend services, handling tasks like session creation, refresh, and invalidation automatically. It operates by intercepting network requests to maintain secure sessions through cookies and headers, without direct communication with the SuperTokens Core service from the frontend. Releases occur frequently, with patch and minor updates weekly or bi-weekly, and major versions typically every few months. Unlike `supertokens-web-js`, which is a plain JavaScript SDK for custom UIs, `supertokens-website` is intended as the foundational frontend SDK that can be used directly or integrated into higher-level framework-specific SDKs (e.g., `supertokens-auth-react`) to provide comprehensive authentication solutions, including pre-built UI components and robust session management features.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the SuperTokens SDK, check for an active user session, retrieve user details, make an authenticated API call, and implement a logout function. It assumes a basic HTML structure with a logout button.

import SuperTokens from "supertokens-website";

SuperTokens.init({
    appInfo: {
        appName: "My SuperTokens Web App",
        apiDomain: "https://api.example.com", // URL of your auth backend
        websiteDomain: "https://app.example.com", // URL of your frontend app
        apiBasePath: "/auth", // Base path for SuperTokens APIs on your backend
        websiteBasePath: "/auth" // Base path for SuperTokens UI on your frontend (if using custom UI)
    },
    // Additional configurations like preAPIHook, postAPIHook, cookieHandler, windowHandler can be added.
    // enableDebugLogs: true, // Uncomment for detailed debug logs in the console.
});

async function handleAuthentication() {
    console.log("Checking session status...");
    const sessionExists = await SuperTokens.doesSessionExist();

    if (sessionExists) {
        const userId = await SuperTokens.getUserId();
        const accessTokenPayload = await SuperTokens.getAccessTokenPayloadSecurely();
        console.log(`User session exists. User ID: ${userId}`);
        console.log("Access Token Payload:", accessTokenPayload);

        // Example of a protected API call
        try {
            const response = await fetch("https://api.example.com/api/data");
            if (response.status === 401) {
                // SuperTokens interceptors should handle session refresh automatically.
                // If refresh fails, it will lead to an unauthenticated state.
                console.warn("API call returned 401. Session might be expired or refresh failed.");
                alert("Your session has expired. Please log in again.");
                await SuperTokens.signOut();
            } else if (response.ok) {
                const data = await response.json();
                console.log("Successfully fetched protected data:", data);
            } else {
                console.error("Failed to fetch protected data:", response.status, response.statusText);
            }
        } catch (error) {
            console.error("Error calling protected API:", error);
        }

        const logoutButton = document.getElementById("logout-btn");
        if (logoutButton) {
            logoutButton.onclick = async () => {
                await SuperTokens.signOut();
                console.log("User signed out.");
                alert("You have been logged out.");
                // Redirect user to login page or update UI state.
            };
        } else {
            console.warn("No element with ID 'logout-btn' found for logout functionality.");
        }
    } else {
        console.log("No active user session. User needs to log in.");
        // Implement logic to show login UI or redirect to login page.
    }
}

// Execute the authentication handler when the DOM is ready.
if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", handleAuthentication);
} else {
    handleAuthentication();
}

view raw JSON →