Frontend Setup
Start the setup by configuring your frontend application to use SuperTokens for authentication.
This guide uses the SuperTokens Pre Built UI components. If you want to create your own interface please check the Custom UI tutorial.
#
1. Install the SDKRun the following command in your terminal to install the package.
- ReactJS
- Angular
- Vue
- Mobile
- Via NPM>=7
- Via NPM6
- Via Yarn
npm i -s supertokens-auth-react
npm i -s supertokens-auth-react supertokens-web-js
yarn add supertokens-auth-react supertokens-web-js
- Via NPM>=7
- Via NPM6
- Via Yarn
Start by installing the SuperTokens Web SDK:
npm i -s supertokens-web-js
Start by installing the SuperTokens Web SDK:
npm i -s supertokens-web-js
Start by installing the SuperTokens Web SDK:
yarn add supertokens-web-js
- Via NPM>=7
- Via NPM6
- Via Yarn
Start by installing the SuperTokens web SDK:
npm i -s supertokens-web-js
Start by installing the SuperTokens web SDK:
npm i -s supertokens-web-js
Start by installing the SuperTokens web SDK:
yarn add supertokens-web-js
important
SuperTokens does not support pre-built UI for mobile frameworks. Please toggle the Custom UI option from the Table of Contents section.
#
2. Initialize the SDK- ReactJS
- Angular
- Vue
- Mobile
In your main application file call the SuperTokens.init
function to initialize the SDK.
The init
call includes the main configuration details, as well as the recipes that you will be using in your setup.
After that you will have to wrap the application with the SuperTokensWrapper
component.
This will provide authentication context for the rest of the UI tree.
You also have to specify which contact method
should be used for the passwordless
flow.
Just click one of the options from the next form and the code snippet will get updated.
import React from 'react';
import SuperTokens, { SuperTokensWrapper } from "supertokens-auth-react";
import Passwordless from "supertokens-auth-react/recipe/passwordless";
import Session from "supertokens-auth-react/recipe/session";
SuperTokens.init({
appInfo: {
appName: "<YOUR_APP_NAME>",
apiDomain: "<YOUR_API_DOMAIN>",
websiteDomain: "<YOUR_WEBSITE_DOMAIN>",
apiBasePath: "/auth",
websiteBasePath: "/auth"
},
recipeList: [
Passwordless.init({
contactMethod: "PHONE"
}),
Session.init()
]
});
/* Your App */
class App extends React.Component {
render() {
return (
<SuperTokensWrapper>
{/*Your app components*/}
</SuperTokensWrapper>
);
}
}
Specify which contact method
should be used for the passwordless
flow.
Just click one of the options from the next form and the code snippet will get updated.
Before we initialize the supertokens-web-js
SDK let's see how we will use it in our Angular app
Architecture
- The
supertokens-web-js
SDK is responsible for session management and providing helper functions to check if a session exists, or validate the access token claims on the frontend (for example, to check for user roles before showing some UI). We will initialise this SDK on the root of your Angular app, so that all pages in your app can use it. - We will create a
/auth*
route in the Angular app which will render our pre built UI which will also need to be initialised, but only on that route.
Creating the /auth
route
Use the Angular CLI to generate a new route
ng generate module auth --route auth --module app.module
Add the following code to your
auth
angular component/app/auth/auth.component.tsimport { Component, OnDestroy, AfterViewInit, Renderer2, Inject } from "@angular/core";
import { DOCUMENT } from "@angular/common";
@Component({
selector: "app-auth",
template: '<div id="supertokensui"></div>',
})
export class AuthComponent implements OnDestroy, AfterViewInit {
constructor(
private renderer: Renderer2,
@Inject(DOCUMENT) private document: Document
) { }
ngAfterViewInit() {
this.loadScript('');
}
ngOnDestroy() {
// Remove the script when the component is destroyed
const script = this.document.getElementById('supertokens-script');
if (script) {
script.remove();
}
}
private loadScript(src: string) {
const script = this.renderer.createElement('script');
script.type = 'text/javascript';
script.src = src;
script.id = 'supertokens-script';
script.onload = () => {
(window as any).supertokensUIInit("supertokensui", {
appInfo: {
appName: "<YOUR_APP_NAME>",
apiDomain: "<YOUR_API_DOMAIN>",
websiteDomain: "<YOUR_WEBSITE_DOMAIN>",
apiBasePath: "/auth",
websiteBasePath: "/auth"
},
recipeList: [
(window as any).supertokensUIPasswordless.init({
contactMethod: "PHONE"
}),
(window as any).supertokensUISession.init(),
],
});
}
this.renderer.appendChild(this.document.body, script);
}
}- In the
loadScript
function, we provide the SuperTokens config for the UI. We add the passwordless and session recipes.
- In the
Initialize the
supertokens-web-js
SDK in your angular app's root component. This will provide session management across your entire application./app/app.component.tsimport SuperTokens from "supertokens-web-js";
import Session from "supertokens-web-js/recipe/session";
SuperTokens.init({
appInfo: {
appName: "<YOUR_APP_NAME>",
apiDomain: "<YOUR_API_DOMAIN>",
apiBasePath: "/auth",
},
recipeList: [
Session.init(),
],
});
Specify which contact method
should be used for the passwordless
flow.
Just click one of the options from the next form and the code snippet will get updated.
Before we initialize the supertokens-web-js
SDK let's see how we will use it in our Vue app
Architecture
- The
supertokens-web-js
SDK is responsible for session management and providing helper functions to check if a session exists, or validate the access token claims on the frontend (for example, to check for user roles before showing some UI). We will initialise this SDK on the root of your Vue app, so that all pages in your app can use it. - We will create a
/auth*
route in the Vue app which will render our pre built UI which will also need to be initialised, but only on that route.
Creating the /auth
route
Create a new file
AuthView.vue
, this Vue component will be used to render the auth component:<script lang="ts">
import { defineComponent, onMounted, onUnmounted } from 'vue';
export default defineComponent({
setup() {
const loadScript = (src: string) => {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
script.id = 'supertokens-script';
script.onload = () => {
(window as any).supertokensUIInit("supertokensui", {
appInfo: {
appName: "<YOUR_APP_NAME>",
apiDomain: "<YOUR_API_DOMAIN>",
websiteDomain: "<YOUR_WEBSITE_DOMAIN>",
apiBasePath: "/auth",
websiteBasePath: "/auth"
},
recipeList: [
(window as any).supertokensUIPasswordless.init({
contactMethod: "PHONE"
}),
(window as any).supertokensUISession.init(),
],
});
};
document.body.appendChild(script);
};
onMounted(() => {
loadScript('');
});
onUnmounted(() => {
const script = document.getElementById('supertokens-script');
if (script) {
script.remove();
}
});
},
});
</script>
<template>
<div id="supertokensui" />
</template>- In the
loadScript
function, we provide the SuperTokens config for the UI. We add the passwordless and session recipes.
- In the
Initialize the
supertokens-web-js
SDK in your Vue app'smain.ts
file. This will provide session management across your entire application./main.tsimport { createApp } from "vue";
import SuperTokens from "supertokens-web-js";
import Session from "supertokens-web-js/recipe/session";
import App from "./App.vue";
import router from "./router";
SuperTokens.init({
appInfo: {
appName: "<YOUR_APP_NAME>",
apiDomain: "<YOUR_API_DOMAIN>",
apiBasePath: "/auth",
},
recipeList: [
Session.init(),
],
});
const app = createApp(App);
app.use(router);
app.mount("#app");
important
SuperTokens does not support pre-built UI for mobile frameworks. Please toggle the Custom UI option from the Table of Contents section.
#
3. Configure Routing- ReactJS
- Angular
- Vue
- Mobile
In order for the Pre Built UI to be rendered inside your application, will will have to specify which routes will show the authentication components. The React SDK uses React Router under the hood to achieve this. Based on whether you already use this package or not in your project, there are two different ways of configuring the routes.
- react-router-dom >= v6
- react-router-dom <= v5
Call the getSuperTokensRoutesForReactRouterDom
method from within any react-router-dom
Routes
component.
import React from 'react';
import {
BrowserRouter,
Routes,
Route,
Link
} from "react-router-dom";
import SuperTokens, { SuperTokensWrapper } from "supertokens-auth-react";
import { getSuperTokensRoutesForReactRouterDom } from "supertokens-auth-react/ui";
import { PasswordlessPreBuiltUI } from 'supertokens-auth-react/recipe/passwordless/prebuiltui';
import * as reactRouterDom from "react-router-dom";
class App extends React.Component {
render() {
return (
<SuperTokensWrapper>
<BrowserRouter>
<Routes>
{/*This renders the login UI on the /auth route*/}
{getSuperTokensRoutesForReactRouterDom(reactRouterDom, [PasswordlessPreBuiltUI])}
{/*Your app routes*/}
</Routes>
</BrowserRouter>
</SuperTokensWrapper>
);
}
}
Call the getSuperTokensRoutesForReactRouterDom
method from within any react-router-dom
Switch
component.
import React from 'react';
import {
BrowserRouter,
Switch,
Route,
Link
} from "react-router-dom";
import SuperTokens, { SuperTokensWrapper } from "supertokens-auth-react";
import { getSuperTokensRoutesForReactRouterDom } from "supertokens-auth-react/ui";
import { PasswordlessPreBuiltUI } from 'supertokens-auth-react/recipe/passwordless/prebuiltui';
import * as reactRouterDom from "react-router-dom";
class App extends React.Component {
render() {
return (
<SuperTokensWrapper>
<BrowserRouter>
<Switch>
{/*This renders the login UI on the /auth route*/}
{getSuperTokensRoutesForReactRouterDom(reactRouterDom, [PasswordlessPreBuiltUI])}
{/*Your app routes*/}
</Switch>
</BrowserRouter>
</SuperTokensWrapper>
);
}
}
Update your angular router so that all auth related requests load the auth
component
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
const routes: Routes = [
{
path: "auth",
loadChildren: () => import("./auth/auth.module").then((m) => m.AuthModule),
},
{ path: "**", loadChildren: () => import("./home/home.module").then((m) => m.HomeModule) },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
Update your Vue router so that all auth related requests load the AuthView
component
import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";
import AuthView from "../views/AuthView.vue";
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: "/",
name: "home",
component: HomeView,
},
{
path: "/auth/:pathMatch(.*)*",
name: "auth",
component: AuthView,
},
],
});
export default router;
important
SuperTokens does not support pre-built UI for mobile frameworks. Please toggle the Custom UI option from the Table of Contents section.
#
4. Handle Session TokensThis part is handled automatically by the Frontend SDK. You don not need to do anything. The step serves more as a way for us to tell you how is this handled under the hood.
After you call the init
function, the SDK will add interceptors to both fetch
and XHR
, XMLHTTPRequest. The latter is used by the axios
library.
The interceptors save the session tokens that are generated from the authentication flow.
Those tokens are then added to requests initialized by your frontend app which target the backend API.
By default, the tokens are stored through session cookies but you can also switch to header based authentication.
#
5. Secure Application RoutesIn order to prevent unauthorized access to ceratain parts of your frontend application you can use our utilities. Follow the code samples below to understand how to do this.
- ReactJS
- Angular
- Vue
You can use the doesSessionExist
function to check if a session exists in all your routes.
import Session from 'supertokens-web-js/recipe/session';
async function doesSessionExist() {
if (await Session.doesSessionExist()) {
// user is logged in
} else {
// user has not logged in yet
}
}
You can wrap your components with the <SessionAuth>
react component. This will ensure that your component renders only if the user is logged in. If they are not logged in, the user will be redirected to the login page.
import React from "react";
import {
BrowserRouter,
Routes,
Route,
} from "react-router-dom";
import { SessionAuth } from "supertokens-auth-react/recipe/session";
import MyDashboardComponent from "./dashboard";
class App extends React.Component {
render() {
return (
<BrowserRouter>
<Routes>
<Route path="/dashboard" element={
<SessionAuth>
{/*Components that require to be protected by authentication*/}
<MyDashboardComponent />
</SessionAuth>
} />
</Routes>
</BrowserRouter>
);
}
}
You can use the doesSessionExist
function to check if a session exists in all your routes.
import Session from 'supertokens-web-js/recipe/session';
async function doesSessionExist() {
if (await Session.doesSessionExist()) {
// user is logged in
} else {
// user has not logged in yet
}
}
#
6. View the login UIYou can check the login UI by visiting the /auth
route, in your frontend application.
To review all the components of our pre-built UI please follow this link.
๐ Congratulations ๐
Congratulations! You've successfully integrated your frontend app with SuperTokens.
The next section will guide you through setting up your backend and then you should be able to complete a login flow.