diff --git a/content/how-to-use-supertokens-pre-built-ui-with-vuejs/index.md b/content/how-to-use-supertokens-pre-built-ui-with-vuejs/index.md index ee5fd731..4ddd3112 100644 --- a/content/how-to-use-supertokens-pre-built-ui-with-vuejs/index.md +++ b/content/how-to-use-supertokens-pre-built-ui-with-vuejs/index.md @@ -1,300 +1,523 @@ --- title: How to use SuperTokens' pre built UI with VueJS -date: "2022-07-13" +date: "2024-09-01" description: "A step by step guide on how to integrate SuperTokens' pre built UI in a VueJS app" cover: "vue-st.png" category: "programming" -author: "Nemi Shah" +author: "Mostafa Ibrahim" --- -Building your own auth service can be tedious, complex and time-consuming. To save time, developers often resort to using third party auth services for auth. This post will guide you on how to add authentication to a VueJS app with SuperTokens. +## Table of Contents + +1. [Introduction](#introduction) +2. [What is SuperTokens?](#what-is-supertokens) +3. [The Modular Architecture of SuperTokens](#the-modular-architecture-of-supertokens) + - [Frontend SDK](#frontend-sdk) + - [Backend SDK](#backend-sdk) + - [Core Microservice](#core-microservice) +4. [Frontend Integration](#frontend-integration) + - [Automatic Setup Using CLI](#automatic-setup-using-cli) + - [Manual Setup Steps](#manual-setup-steps) + - [Install SuperTokens Web SDK](#install-supertokens-web-sdk) + - [Create HomeView.vue](#create-homeviewvue) + - [Architecture of SuperTokens SDK Setup](#architecture-of-supertokens-sdk-setup) + - [Creating the /auth Route](#creating-the-auth-route) + - [Initialize SuperTokens in main.ts](#initialize-supertokens-in-maints) + - [Setup Routing to Show the Login UI](#setup-routing-to-show-the-login-ui) + - [View the Login UI](#view-the-login-ui) +5. [Backend Integration](#backend-integration) + - [Install Backend SDK](#install-backend-sdk) + - [Initialize SuperTokens](#initialize-supertokens) + - [Initialize Social Login Providers](#initialize-social-login-providers) + - [Add the SuperTokens APIs & CORS Setup](#add-the-supertokens-apis--cors-setup) + - [Add the SuperTokens Error Handler](#add-the-supertokens-error-handler) +6. [SuperTokens Core Setup](#supertokens-core-setup) + - [Self-hosted Setup](#self-hosted-setup) + - [Managed Service](#managed-service) +7. [Conclusion](#conclusion) + +Building a secure and scalable authentication system from scratch can be a daunting task. Fortunately, SuperTokens is here to simplify the process and help you add robust authentication to your Vue.js application in no time. In this step-by-step guide, we'll walk you through the integration of SuperTokens' pre-built UI into your Vue.js app, allowing you to focus on building the core features of your application. ## What is SuperTokens? -[SuperTokens](https://supertokens.com) is an open source project which enables you to add auth to your app quickly. It gives you a pre-built auth UI and backend APIs for an end-to-end integration experience. +SuperTokens is an open-source project that enables you to add auth to your app quickly. It gives you a pre-built auth UI and backend APIs for an end-to-end integration experience. Before we dive into the code, let’s discuss the overall architecture. -## Architecture +## The Modular Architecture of SuperTokens -SuperTokens is built out of three components: -- Frontend SDK -- Backend SDK -- Core microservice that talks to a database. +SuperTokens' architecture is designed to be modular and flexible, consisting of three main components: -We’ll use the SuperTokens frontend SDK in our Vue app to add all the auth forms (login, signup, reset password etc). You can also build your own UI using the helper functions from frontend SDKs, but we will focus on the pre built UI in this blog. +- **Frontend SDK**: This is the library you'll use in your Vue.js app to render the pre-built authentication UI, including login, signup, and password reset forms. +- **Backend SDK**: This is the library you'll use in your backend to expose the authentication-related API endpoints. +- **Core Microservice**: This is the central service that handles all the authentication logic and communicates with the database. It can either be self-hosted using Docker or AWS, or it can be a managed service handled by the SuperTokens team. -The pre built UI are ReactJS components (provided by the [`supertokens-auth-react` library](https://github.com/supertokens/supertokens-auth-react)). In order to use them, we will have to render React components in our VueJS app. +SuperTokens simplifies authentication integration by separating its components, enabling you to incorporate secure user management into your app effortlessly. This approach shields you from the intricacies of authentication systems, allowing you to focus on your core application logic. -For the backend, we will use the NodeJS SDK provided by SuperTokens ([`supertokens-node` library](https://github.com/supertokens/supertokens-node)). This SDK exposes all of the auth APIs (like `/auth/signin`, `/auth/signout` etc) via a middleware, for the frontend to call. When these APIs are called, the SDK will talk to the SuperTokens Core microservice to read and write information to the database. +The modular structure of SuperTokens facilitates a straightforward implementation process, which we'll explore in detail through a step-by-step guide to setting up this powerful authentication solution in your project. -The SuperTokens core service can be either self hosted (and connected to your own db), or be hosted by the team behind SuperTokens (sign up on [supertokens.com](https://supertokens.com)). - -> In order to keep the app’s bundle size small, we will limit the use of the `supertokens-auth-react` SDK to all of the auth related routes (`/auth/*` by default), and use a lighter weight, vanilla JS SDK ([`supertokens-web-js` library](https://github.com/supertokens/supertokens-web-js)) for all other routes in our app. Finally, we will then use code splitting and lazy importing to make sure that the `supertokens-auth-react` SDK is only bundled when visiting the `/auth/*` routes. - -![img](./self_hosted.png) ## Frontend Integration -### 1. Setup and Install +SuperTokens offers an easy way to integrate authentication into your Vue.js application using its pre-built UI. Whether you're using React, Angular, or Vue.js, SuperTokens provides support across various frameworks. For mobile apps, please see the "Using your own UI" section in the SuperTokens documentation. -Create a new Vue + Typescript app: +### Automatic Setup Using CLI + +For the quickest setup, run the following command in your terminal: ```bash -npm init vue@latest +npx create-supertokens-app@latest --recipe=thirdpartyemailpassword ``` -In the prompt, select Typescript and Vue Router: +This command automatically sets up your project with SuperTokens' Third-Party Email Password recipe. Once this is done, you can skip steps 1 and 2 in this section and move directly to setting up the SuperTokens core (Step 3). + +Alternatively, you can manually integrate SuperTokens by following the steps below. -![img](./Creating_a_new_vue_project.png) +### Manual Setup Steps -Once that’s done, head inside the project and install the following dependencies: +1. **Install SuperTokens Web SDK** +    Start by installing the SuperTokens web SDK using the following command: ```bash -npm i --save cors express npm-run-all react supertokens-auth-react react-dom supertokens-node +npm install supertokens-web-js ``` -The `supertokens-auth-react` library will be used on the frontend to render the login UI, and the `supertokens-node` library will be used on the backend to expose the auth API routes. +2. **Initialize the SuperTokens SDK** -### 2. Call the `supertokens-auth-react` and `supertokens-web-js` `init` function +Before initializing the SuperTokens SDK, let's explore how to integrate it into our Vue app. -Start by create the `AuthView` component inside `/src/views` folder. This component will render the SuperTokens React component to handle authentication on the frontend: +But first, let's create a `HomeView` to have an unprotected route from which we can do the login. + +#### Create HomeView.vue + +Create a new file named `HomeView.vue` in your `src/views` directory and add the following code: ```html -``` - -Notice that we have made a `
` element with the `id="authId"`. This is where we will render the react components provided by SuperTokens. -Next, let's create a file - `/src/components/Supertokens.tsx` which is the actual React component that we will be rendering. Inside this file, we will initialize the `supertokens-auth-react` SDK and use it in the React `render` function. - -```ts -import * as React from "react"; -import * as SuperTokens from "supertokens-auth-react"; -import * as ThirdPartyEmailPassword from "supertokens-auth-react/recipe/thirdpartyemailpassword"; -import { Github, Google } from "supertokens-auth-react/recipe/thirdpartyemailpassword"; -import Session from "supertokens-auth-react/recipe/session"; + +``` -SuperTokens.init({ - appInfo: { - appName: "SuperTokens Demo App", - apiDomain: "http://localhost:3001", - websiteDomain: "http://localhost:4200", - }, - recipeList: [ - ThirdPartyEmailPassword.init({ - signInAndUpFeature: { - providers: [Github.init(), Google.init()], - } - }), - Session.init(), - ], -}); +### Architecture of SuperTokens SDK Setup -class SuperTokensReactComponent extends React.Component { - override render() { - if (SuperTokens.canHandleRoute()) { - return SuperTokens.getRoutingComponent(); - } - return "Route not found"; - } -} +The `supertokens-web-js` SDK is responsible for session management and providing helper functions to check if a session exists or validate access token claims on the frontend. We will initialize this SDK in the root of your Vue app so that all pages can use it. -export default SuperTokensReactComponent; -``` +We will create an `/auth*` route in the Vue app to render the pre-built UI, which will also need to be initialized, but only on that route. -> The snippet above uses the `ThirdPartyEmailPassword` recipe (social + email / password login). You can choose another recipe as well by following the quick setup section in the [guides on supertokens.com](https://supertokens.com/docs/guides). +### Creating the /auth Route -Next, we will load this `SuperTokensReactComponent` inside the `AuthView` component: +Create a new file `AuthView.vue`. This Vue component will be used to render the auth component: ```html + + ``` -The above takes care of the `/auth/*` related routes. For all the other pages in our app, we want to be able to know if a session exists and extract information from it. To do this, we will use the `supertokens-web-js` SDK. We initialize this SDK in our Vue app's root file `/src/main.ts`: +In the `loadScript` function, we provide the SuperTokens config for the UI. This includes email-password, session, and social login recipes with GitHub, Google, Facebook, and Apple login buttons. -```ts -import Vue from "vue"; -import VueCompositionAPI, { createApp, h } from "@vue/composition-api"; -import * as SuperTokens from "supertokens-web-js"; -import * as Session from "supertokens-web-js/recipe/session"; +### main.ts +Next, initialize the `supertokens-web-js` SDK in your Vue app's `main.ts` file. This will provide session management across your entire application. + +Copy and paste this in your `main.ts`: + +```ts +import { 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: "SuperTokens Demo", - apiDomain: "http://localhost:3001", + appName: "", + apiDomain: "", + apiBasePath: "/auth", }, - recipeList: [Session.init()], + recipeList: [ + Session.init(), + ], }); -Vue.use(VueCompositionAPI); - -const app = createApp({ - router, - render: () => h(App), -}); +const app = createApp(App); +app.use(router); app.mount("#app"); ``` -> The config for the `Session.init` call, the `apiDomain` and the `appName` for both the `init` functions (`supertokens-auth-react` and `supertokens-web-js`) should always be the same. - -### 3. Setup Routing to show the Login UI +### 3) Setup Routing to Show the Login UI -Vue CLI already generates the initial routing for our app inside `/src/router.index.ts`. We'll update this file so that all `/auth/*` routes load the `AuthView` component we created earlier: +Update your Vue router so that all auth-related requests load the `AuthView` component. ```ts -import Vue from 'vue' -import VueRouter from 'vue-router' -import HomeView from '../views/HomeView.vue' - -Vue.use(VueRouter) - -const router = new VueRouter({ - mode: 'history', - base: import.meta.env.BASE_URL, - routes: [{ - path:'/auth*', - name:'auth', - component: () => import('../views/AuthView.vue'), - }] -}) - -export default router +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",\ +            name: "auth",\ +            component: AuthView,\ +        },\ +    ],\ +}); + +export default router; ``` -The path for the `AuthView` component is `/auth*`. The `*` indicates that any sub / nested paths with `/auth` as the parent path should be rendered by the `AuthView` component. The `AuthView` component will in turn render the ReactJS component we created earlier which will use the `supertokens-auth-react` SDK to show the auth UI. +### 4) View the Login UI -We lazy load the `/auth` route because the `AuthView` component loads ReactJS as a dependency. Lazy loading makes sure that these dependencies are only injected in the `AuthView` component when you visit the `/auth/*` routes. For all of the other routes, these dependencies are not imported thereby maintaining the overall bundle size of the application. +You can view the login UI by visiting /auth in your browser. You can also see all the designs of the pre-built UI for each page on this [link](https://master--6571be2867f75556541fde98.chromatic.com/?path=/story/auth-page--playground). +![login form](./st-loginform.png) -### 4. View the Login UI +At this stage, you've successfully integrated your front end with SuperTokens. The next section will guide you through setting up your backend. -If you now visit http://localhost:4200/auth, you should see the login UI as shown below: -![img](./Auth_View_Demo.png) +### Backend Integration -## Backend Integration +SuperTokens provides a powerful backend authentication service that can be easily integrated with various backend frameworks like Node.js, GoLang, Python, and others. This guide will walk you through setting up SuperTokens with Node.js, specifically using Express. -You can see the backend quick setup section [in our docs on supertokens.com](https://supertokens.com/docs/thirdpartyemailpassword/quick-setup/backend), or even copy the code from [our example app](https://github.com/supertokens/supertokens-auth-react/blob/master/examples/with-vue-thirdpartyemailpassword/server.ts). As a summary: +#### 1. Install Backend SDK -- You need to initialize the `supertokens-node` SDK and provide it the `recipeList` (similar to how you did on the frontend). -- Then you need to setup `CORS`, add the SuperTokens `middleware` and `errorHandler` to your app. The SuperTokens `middleware` exposes all the auth related API routes (like sign in, sign up, sign out etc) to the frontend. -- Finally, you need to provide the `connectionURI` (location) of the SuperTokens core. To get started quickly, you can provide it `https://try.supertokens.com` (this is a core that we host for demo purposes). +Begin by installing the SuperTokens Node SDK via npm: -Once you’ve successfully setup your server, you can now try and sign up on the frontend. +```bash +npm install supertokens-node +``` -## Session management +#### 2. Initialize SuperTokens -Inside `/src/views/HomeView.vue` file we'll check if the user is authenticated and conditionally render a template. For authenticated users, we can show them a logout button with information about their session (like their `userId`). For unauthenticated users, we can show them a button to route to the `/auth` page. +To get started, you need to initialize SuperTokens in your server's initialization file. Here's how you can do it with Node.js: ```ts - + recipeList: [ + EmailPassword.init(), + ThirdParty.init({ + // Add third-party login providers in the next step + }), + Session.init(), // Initializes session features + ] +}); - ``` -To load the `HomeView` component on `/` we'll update the `/src/router/index.ts` file: +### 3) Initialize Social Login Providers + +To enable third-party authentication, populate the providers array with the relevant OAuth providers. Here's an example: + +Copy this code and replace SuperTokens.init() in the above server initialization file: + +### Final Thoughts + +With just a few lines of code, you've added a fully functional, pre-built authentication UI to your Vue.js application. SuperTokens allows you to integrate email/password and social logins easily, and its modular architecture ensures that it's flexible enough for your specific use case. + +For more advanced use cases, such as customizing the login UI or handling multiple recipes in parallel, be sure to check out the official SuperTokens documentation. ```ts -const router = new VueRouter({ - // ... - routes: [{ - path: "/", - name: "home", - component: HomeView, - }, /*...*/], +SuperTokens.init({ + appInfo: { + apiDomain: "", + appName: "", + websiteDomain: "", + }, + recipeList: [ + EmailPassword.init() + ThirdParty.init({ + signInAndUpFeature: { + providers: [ + { + config: { + thirdPartyId: "google", + clients: [{ + clientId: "YOUR_GOOGLE_CLIENT_ID", + clientSecret: "YOUR_GOOGLE_CLIENT_SECRET" + }] + } + }, + { + config: { + thirdPartyId: "github", + clients: [{ + clientId: "YOUR_GITHUB_CLIENT_ID", + clientSecret: "YOUR_GITHUB_CLIENT_SECRET" + }] + } + }, + { + config: { + thirdPartyId: "apple", + clients: [{ + clientId: "YOUR_APPLE_CLIENT_ID", + additionalConfig: { + keyId: "YOUR_KEY_ID", + privateKey: "YOUR_PRIVATE_KEY", + teamId: "YOUR_TEAM_ID" + } + }] + } + } + ], + } + }), + + ] }); ``` -If you now visit http://localhost:4200, you should see the following page: +Ensure that you replace the placeholder values ("YOUR_GOOGLE_CLIENT_ID", "YOUR_GOOGLE_CLIENT_SECRET", etc.) with your actual OAuth credentials. For production, make sure to use your own OAuth keys. + +### 4) Add the SuperTokens APIs & CORS Setup + +You need to set up middleware in your Express application to handle SuperTokens' APIs and manage CORS. Add this configuration before all your routes in your backend's index.ts: + + +```ts +import express from "express"; +import cors from "cors"; +import supertokens from "supertokens-node"; +import { middleware } from "supertokens-node/framework/express"; + + +let app = express(); + + +app.use(cors({ + origin: "", + allowedHeaders: ["content-type", ...supertokens.getAllCORSHeaders()], + credentials: true, +})); + + +// IMPORTANT: CORS should be configured before the SuperTokens middleware. +app.use(middleware()); + + +// Define your API routes here +``` + +This middleware setup adds several key APIs, including: + +- POST /auth/signinup: For signing up/signing in a user using a third-party provider. +- POST /auth/signup: For signing up a user with email & password. +- POST /auth/signin: For signing in a user with email & password. + + +### 5) Add the SuperTokens Error Handler + +To properly handle errors related to SuperTokens, add the following error handler middleware after your routes in your backend's index.ts: + +```ts +import { errorHandler } from "supertokens-node/framework/express"; +import express from "express"; + + +let app = express(); + + +// Define your API routes here + + +// Add the SuperTokens error handler after your routes +app.use(errorHandler()); + + +// Your custom error handler +app.use((err, req, res, next) => { + // Handle errors +}); +``` -![img](./Signed_In.png) ## SuperTokens Core Setup -Whilst doing the backend setup, we are using `https://try.supertokens.com` as the `connectionURI` for the core. This is a demo core instance hosted by the team of SuperTokens. You can use this for as long as you like, but when you are committed to using SuperTokens, you should switch to a [self hosted](https://supertokens.com/docs/thirdpartyemailpassword/quick-setup/core/with-docker) or a [managed version](https://supertokens.com/docs/thirdpartyemailpassword/quick-setup/core/saas-setup) of the core. +During the backend setup, we are using https://try.supertokens.com as the connectionURI for the Core, which is a demo instance hosted by the SuperTokens team. This instance is available for as long as needed, but once you decide to fully integrate SuperTokens into your application, it's recommended to transition to either a self-hosted or managed version of the Core. -## Conclusion +For a [self-hosted](https://supertokens.com/docs/thirdpartyemailpassword/pre-built-ui/setup/core/without-docker) setup, you can deploy the Core using [Docker](https://supertokens.com/docs/thirdpartyemailpassword/pre-built-ui/setup/core/with-docker) or through cloud platforms like [AWS](https://supertokens.com/docs/thirdpartyemailpassword/pre-built-ui/setup/core/aws-setup-with-stacksnap). This option offers greater control over your infrastructure, allowing you to customize the deployment according to your specific needs. -To summarise, we used the ReactJS SDK provided by SuperTokens to show the pre-built login UI for our Vue app. We also optimised the bundle size so that the ReactJS SDK is only loaded for auth related routes. -Useful links: +Alternatively, SuperTokens offers a [managed service](https://supertokens.com/docs/thirdpartyemailpassword/pre-built-ui/setup/core/saas-setup), where they handle the hosting and maintenance of the Core for you. This option provides the advantage of reduced operational overhead, as the SuperTokens team manages updates, scaling, and security for you. + + +## Conclusion -- [Example Vue app](https://github.com/supertokens/supertokens-auth-react/tree/master/examples/with-vue-thirdpartyemailpassword) -- [Discord community (to ask questions)](https://supertokens.com/discord) -- [List of recipes / auth methods](https://supertokens.com/docs/guides) +By following this guide, you've successfully integrated SuperTokens' pre-built authentication UI into your Vue.js application. With this setup in place, you can now concentrate on developing your app's core features, while SuperTokens takes care of the complexities of user authentication. +For additional information and advanced use cases, be sure to explore the detailed [documentation](https://supertokens.com/docs/thirdpartyemailpassword/introduction) available on the SuperTokens website. Should you have any questions or require further assistance, the SuperTokens team is always ready to help. \ No newline at end of file diff --git a/content/how-to-use-supertokens-pre-built-ui-with-vuejs/st-loginform.png b/content/how-to-use-supertokens-pre-built-ui-with-vuejs/st-loginform.png new file mode 100644 index 00000000..b08337de Binary files /dev/null and b/content/how-to-use-supertokens-pre-built-ui-with-vuejs/st-loginform.png differ