Skip to content

Files

699 lines (525 loc) · 18 KB

frontend.mdx

File metadata and controls

699 lines (525 loc) · 18 KB
id title hide_title
frontend
Step 1: Frontend
true

import { PasswordlessFrontendForm } from "/src/components/snippetConfigForm/passwordlessFrontendForm";

import FrontendPreBuiltUITabs from "/src/components/tabs/FrontendPreBuiltUITabs" import TabItem from '@theme/TabItem'; import {Question, Answer}from "/src/components/question" import AppInfoForm from "/src/components/appInfoForm" import RRDVersionSubTabs from "/src/components/tabs/RRDVersionSubTabs" import NpmVersionOrYarnSubTabs from "/src/components/tabs/NpmVersionOrYarnSubTabs" import PreBuiltUIInjector from "/src/components/prebuiltuiInjector"

Frontend Integration

Supported frameworks

import TechStackSupport from "../../../community/reusableMD/supported-tech-stacks-frontend.mdx"

Automatic setup using CLI

Run the following command in your terminal.

npx create-supertokens-app@latest --recipe=^{docsLinkRecipeName}

Once this is done, you can skip Step (1) and (2) in this section (see left nav bar) and move directly to setting up the SuperTokens core (Step 3).

Or, you can manually integrate SuperTokens by following the steps below.

Manual setup steps below

1) Install

npm i -s supertokens-auth-react
npm i -s supertokens-auth-react supertokens-web-js
yarn add supertokens-auth-react supertokens-web-js
pnpm add supertokens-auth-react supertokens-web-js

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

Start by installing the SuperTokens Web SDK:

pnpm add supertokens-web-js

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

Start by installing the SuperTokens web SDK:

pnpm add supertokens-web-js

:::important SuperTokens does not support pre-built UI for mobile frameworks. Please refer to the setup guide for custom UI to integrate SuperTokens in your app. :::

2) Call the init function

<AppInfoForm askForAppName askForAPIDomain askForWebsiteDomain

import React from 'react';

// highlight-start
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: "^{form_appName}",
        apiDomain: "^{form_apiDomain}",
        websiteDomain: "^{form_websiteDomain}",
        apiBasePath: "^{form_apiBasePath}",
        websiteBasePath: "^{form_websiteBasePath}"
    },
    recipeList: [
        Passwordless.init({
            contactMethod: "^{form_contactMethod}"
        }),
        Session.init()
    ]
});
// highlight-end


/* Your App */
class App extends React.Component {
    render() {
        return (
            // highlight-next-line
            <SuperTokensWrapper>
                {/*Your app components*/}
            // highlight-next-line
            </SuperTokensWrapper>
        );
    }
}

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 ^{form_websiteBasePath}* 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 ^{form_websiteBasePath} 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

    import {init as supertokensUIInit} from "supertokens-auth-react-script";
    import supertokensUIPasswordless from "supertokens-auth-react-script/recipe/passwordless";
    import supertokensUISession from "supertokens-auth-react-script/recipe/session";
    import { 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('^{jsdeliver_prebuiltui}');
        }
    
        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 = () => {
                supertokensUIInit({
                    appInfo: {
                        appName: "^{form_appName}",
                        apiDomain: "^{form_apiDomain}",
                        websiteDomain: "^{form_websiteDomain}",
                        apiBasePath: "^{form_apiBasePath}",
                        websiteBasePath: "^{form_websiteBasePath}"
                    },
                    recipeList: [
                        supertokensUIPasswordless.init({
                            contactMethod: "^{form_contactMethod}"
                        }),
                        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.
  • Initialize the supertokens-web-js SDK in your angular app's root component. This will provide session management across your entire application.

    import SuperTokens from "supertokens-web-js";
    import Session from "supertokens-web-js/recipe/session";
    
    SuperTokens.init({
        appInfo: {
            appName: "^{form_appName}",
            apiDomain: "^{form_apiDomain}",
            apiBasePath: "^{form_apiBasePath}",
        },
        recipeList: [
            Session.init(),
        ],
    });

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 ^{form_websiteBasePath}* 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 ^{form_websiteBasePath} route

  • Create a new file AuthView.vue, this Vue component will be used to render the auth component:

    import {init as supertokensUIInit} from "supertokens-auth-react-script";
    import supertokensUIPasswordless from "supertokens-auth-react-script/recipe/passwordless";
    import supertokensUISession from "supertokens-auth-react-script/recipe/session";
    <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 = () => {
                        supertokensUIInit({
                            appInfo: {
                                appName: "^{form_appName}",
                                apiDomain: "^{form_apiDomain}",
                                websiteDomain: "^{form_websiteDomain}",
                                apiBasePath: "^{form_apiBasePath}",
                                websiteBasePath: "^{form_websiteBasePath}"
                            },
                            recipeList: [
                                supertokensUIPasswordless.init({
                                    contactMethod: "^{form_contactMethod}"
                                }),
                                supertokensUISession.init(),
                            ],
                        });
                    };
                    document.body.appendChild(script);
                };
    
                onMounted(() => {
                    loadScript('^{jsdeliver_prebuiltui}');
                });
    
                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.
  • Initialize the supertokens-web-js SDK in your Vue app's main.ts file. This will provide session management across your entire application.

    // @ts-ignore
    import { createApp } from "vue";
    import SuperTokens from "supertokens-web-js";
    import Session from "supertokens-web-js/recipe/session";
    // @ts-ignore
    import App from "./App.vue";
    // @ts-ignore
    import router from "./router";
    
    SuperTokens.init({
        appInfo: {
            appName: "^{form_appName}",
            apiDomain: "^{form_apiDomain}",
            apiBasePath: "^{form_apiBasePath}",
        },
        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 refer to the setup guide for custom UI to integrate SuperTokens in your app. :::

3) Setup Routing to show the login UI

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";

// highlight-next-line
import SuperTokens, { SuperTokensWrapper } from "supertokens-auth-react";
import { getSuperTokensRoutesForReactRouterDom } from "supertokens-auth-react/ui";
^{prebuiltuiimport}
import * as reactRouterDom from "react-router-dom";

class App extends React.Component {
    render() {
        return (
            <SuperTokensWrapper>
                <BrowserRouter>
                    <Routes>
                        {/*This renders the login UI on the ^{form_websiteBasePath} route*/}
                        // highlight-next-line
                        {getSuperTokensRoutesForReactRouterDom(reactRouterDom, [^{recipePreBuiltUINameCapitalLetters}])}
                        {/*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-dom5";

// highlight-next-line
import SuperTokens, { SuperTokensWrapper } from "supertokens-auth-react";
import { getSuperTokensRoutesForReactRouterDom } from "supertokens-auth-react/ui";
^{prebuiltuiimport}
import * as reactRouterDom from "react-router-dom";


class App extends React.Component {
    render() {
        return (
            <SuperTokensWrapper>
                <BrowserRouter>
                    <Switch>
                        {/*This renders the login UI on the ^{form_websiteBasePath} route*/}
                        // highlight-next-line
                        {getSuperTokensRoutesForReactRouterDom(reactRouterDom, [^{recipePreBuiltUINameCapitalLetters}])}
                        {/*Your app routes*/}
                    </Switch>
                </BrowserRouter>
            </SuperTokensWrapper>
        );
    }
}

Add the highlighted code snippet to your root level render function.

import React from 'react';
^{prebuiltuiimport}
import SuperTokens, { SuperTokensWrapper } from "supertokens-auth-react";
import { canHandleRoute, getRoutingComponent } from "supertokens-auth-react/ui";

class App extends React.Component {
    render() {
        // highlight-start
        if (canHandleRoute([^{recipePreBuiltUINameCapitalLetters}])) {
            // This renders the login UI on the ^{form_websiteBasePath} route
            return getRoutingComponent([^{recipePreBuiltUINameCapitalLetters}])
        }
        // highlight-end

        return (
            <SuperTokensWrapper>{/*Your app*/}</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 = [
    // highlight-start
    {
        path: "^{form_websiteBasePath_withoutForwardSlash}",
        // @ts-ignore
        loadChildren: () => import("./auth/auth.module").then((m) => m.AuthModule),
    },

    // @ts-ignore
    { path: "**", loadChildren: () => import("./home/home.module").then((m) => m.HomeModule) },
    // highlight-end
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule],
})
export class AppRoutingModule {}

Update your Vue router so that all auth related requests load the AuthView component

// @ts-ignore
import { createRouter, createWebHistory } from "vue-router";
// @ts-ignore
import HomeView from "../views/HomeView.vue";
// @ts-ignore
import AuthView from "../views/AuthView.vue";

const router = createRouter({
    // @ts-ignore
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: "/",
            name: "home",
            component: HomeView,
        },
        {
            path: "^{form_websiteBasePath}/:pathMatch(.*)*",
            name: "auth",
            component: AuthView,
        },
    ],
});

export default router;

:::important SuperTokens does not support pre-built UI for mobile frameworks. Please refer to the setup guide for custom UI to integrate SuperTokens in your app. :::

4) View the login UI

<AppInfoForm askForWebsiteBasePath addVisitWebsiteBasePathText

^{form_addVisitWebsiteBasePathText}

At this stage, you've successfully integrated your website with SuperTokens. The next section will guide you through setting up your backend.