{"id":16688,"library":"supertokens-website","title":"SuperTokens Website Frontend SDK","description":"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.","status":"active","version":"20.1.6","language":"javascript","source_language":"en","source_url":"https://github.com/supertokens/supertokens-website","tags":["javascript","auth","authentication","authorisation","supertokens","chrome","firefox","IE","safari"],"install":[{"cmd":"npm install supertokens-website","lang":"bash","label":"npm"},{"cmd":"yarn add supertokens-website","lang":"bash","label":"yarn"},{"cmd":"pnpm add supertokens-website","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary entry point for initializing the SDK and accessing core session methods. Primarily designed for ESM environments, CommonJS `require` is generally incorrect.","wrong":"const SuperTokens = require('supertokens-website');","symbol":"SuperTokens","correct":"import SuperTokens from 'supertokens-website';"},{"note":"Checks if an active user session exists. Can also be accessed via `SuperTokens.doesSessionExist()` after initialization.","symbol":"doesSessionExist","correct":"import { doesSessionExist } from 'supertokens-website';"},{"note":"Revokes the current user session on both frontend and backend. Can also be accessed via `SuperTokens.signOut()`.","symbol":"signOut","correct":"import { signOut } from 'supertokens-website';"},{"note":"Utility function to integrate SuperTokens session handling with Axios HTTP client. Call `addAxiosInterceptors(axios)` after initializing SuperTokens.","symbol":"addAxiosInterceptors","correct":"import { addAxiosInterceptors } from 'supertokens-website';"}],"quickstart":{"code":"import SuperTokens from \"supertokens-website\";\n\nSuperTokens.init({\n    appInfo: {\n        appName: \"My SuperTokens Web App\",\n        apiDomain: \"https://api.example.com\", // URL of your auth backend\n        websiteDomain: \"https://app.example.com\", // URL of your frontend app\n        apiBasePath: \"/auth\", // Base path for SuperTokens APIs on your backend\n        websiteBasePath: \"/auth\" // Base path for SuperTokens UI on your frontend (if using custom UI)\n    },\n    // Additional configurations like preAPIHook, postAPIHook, cookieHandler, windowHandler can be added.\n    // enableDebugLogs: true, // Uncomment for detailed debug logs in the console.\n});\n\nasync function handleAuthentication() {\n    console.log(\"Checking session status...\");\n    const sessionExists = await SuperTokens.doesSessionExist();\n\n    if (sessionExists) {\n        const userId = await SuperTokens.getUserId();\n        const accessTokenPayload = await SuperTokens.getAccessTokenPayloadSecurely();\n        console.log(`User session exists. User ID: ${userId}`);\n        console.log(\"Access Token Payload:\", accessTokenPayload);\n\n        // Example of a protected API call\n        try {\n            const response = await fetch(\"https://api.example.com/api/data\");\n            if (response.status === 401) {\n                // SuperTokens interceptors should handle session refresh automatically.\n                // If refresh fails, it will lead to an unauthenticated state.\n                console.warn(\"API call returned 401. Session might be expired or refresh failed.\");\n                alert(\"Your session has expired. Please log in again.\");\n                await SuperTokens.signOut();\n            } else if (response.ok) {\n                const data = await response.json();\n                console.log(\"Successfully fetched protected data:\", data);\n            } else {\n                console.error(\"Failed to fetch protected data:\", response.status, response.statusText);\n            }\n        } catch (error) {\n            console.error(\"Error calling protected API:\", error);\n        }\n\n        const logoutButton = document.getElementById(\"logout-btn\");\n        if (logoutButton) {\n            logoutButton.onclick = async () => {\n                await SuperTokens.signOut();\n                console.log(\"User signed out.\");\n                alert(\"You have been logged out.\");\n                // Redirect user to login page or update UI state.\n            };\n        } else {\n            console.warn(\"No element with ID 'logout-btn' found for logout functionality.\");\n        }\n    } else {\n        console.log(\"No active user session. User needs to log in.\");\n        // Implement logic to show login UI or redirect to login page.\n    }\n}\n\n// Execute the authentication handler when the DOM is ready.\nif (document.readyState === \"loading\") {\n    document.addEventListener(\"DOMContentLoaded\", handleAuthentication);\n} else {\n    handleAuthentication();\n}\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Ensure your SuperTokens backend SDK (e.g., `supertokens-node`) is updated to a compatible version and is correctly sending the `front-token` header with refresh responses. Verify backend API configurations.","message":"The SDK now throws an error if the 'front-token' header is missing on a successful session refresh response from the backend. This enforces stricter compliance with expected backend behavior.","severity":"breaking","affected_versions":">=20.1.5"},{"fix":"Review and test your application's `apiDomain` and `sessionTokenBackendDomain` configurations, especially if your frontend and backend operate on different subdomains or ports within the same root domain. Adjust URL interception logic if custom behavior was previously relied upon.","message":"The behavior of `shouldDoInterceptionBasedOnUrl` changed. It now returns `true` for valid subdomains of `sessionTokenBackendDomain` and for requests with different ports but the same hostname or subdomain. This aligns cookie handling with browser behavior.","severity":"breaking","affected_versions":">=20.0.0"},{"fix":"Update all instances where `validatorId` is used in your code to `id`. This includes any custom claim validators or logic interacting with claim properties.","message":"The `validatorId` property used in session claims has been renamed to `id`.","severity":"breaking","affected_versions":">=19.0.0"},{"fix":"Replace all calls to `getJWTPayloadSecurely()` with `getAccessTokenPayloadSecurely()` to retrieve the access token payload.","message":"The method `getJWTPayloadSecurely` was renamed to `getAccessTokenPayloadSecurely`.","severity":"breaking","affected_versions":">=10.0.0"},{"fix":"Instruct users to enable third-party cookies or ensure your application is configured for first-party cookie usage. Debug with `enableDebugLogs: true` in `init()` to see specific warnings related to cookie writing failures.","message":"A session refresh loop can occur if the browser's cookie writes are disabled (e.g., by privacy settings or extensions). The SDK will now provide console warnings/errors to help diagnose this.","severity":"gotcha","affected_versions":">=20.1.2"},{"fix":"Configure your backend's CORS policy to explicitly allow the necessary headers: `Access-Control-Allow-Headers: Content-Type, Authorization, rid, fdi-version, anti-csrf, st-auth-mode`. Also ensure `Access-Control-Allow-Credentials` is set to `true` and `Access-Control-Allow-Origin` is correctly configured for your frontend domain.","message":"Incorrect CORS configuration on your backend can prevent session management. Specifically, the `Access-Control-Allow-Headers` must include `rid, fdi-version, anti-csrf, st-auth-mode`.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure browser cookies are enabled for your domain. Update `supertokens-website` to the latest version (>=20.1.2) to mitigate known issues. Verify backend SuperTokens SDK is updated and configured for correct session handling. If using a proxy/API gateway (like Vercel), ensure auth API responses are not cached (e.g., by setting `Cache-Control: no-store` header).","cause":"Multiple potential causes including disabled cookie writes, incorrect backend configuration, or misconfigured API Gateway caching.","error":"Session refresh loop detected or session not being maintained."},{"fix":"Update `supertokens-website` to version >=20.1.0 which includes a fix for handling non-JSON bodies in XMLHttpRequest. Additionally, ensure your backend's SuperTokens endpoints consistently return valid JSON responses for all statuses.","cause":"An API endpoint, particularly a SuperTokens endpoint, returned a non-JSON response body when JSON was expected (e.g., plain text or HTML error page).","error":"JSON.parse: unexpected non-whitespace character at line 1 column 1 of the JSON data"},{"fix":"Update your SuperTokens backend SDK to a compatible version and verify its configuration to ensure it sends the `front-token` header as part of the refresh response. This is a critical component for frontend session state management. This started to throw an error since v20.1.5.","cause":"The SuperTokens backend is not including the required `front-token` header in the response to a successful session refresh request.","error":"Missing 'front-token' header in successful refresh response."}],"ecosystem":"npm"}