FusionAuth QuickStart for Vue.js

On this page

This QuickStart adds login and a protected page to a Vue.js web app using a preconfigured, local version of FusionAuth in the following steps:

  1. Create a new Vue app.
  2. Customize the app with home and account pages.
  3. Add login to protect the account page.
  4. Give each user their own note on the account page.

Prerequisites#

This QuickStart requires:

If you use macOS or Windows, you need one of the following container management tools:

  • Docker Desktop
  • OrbStack (to use OrbStack for docker compose commands after installation, run docker context use orbstack)
  • Podman (in the commands below, replace docker with podman)

Install and Run FusionAuth#

To begin, clone the GitHub repository for this QuickStart to your local machine:

$ git clone https://github.com/FusionAuth/fusionauth-quickstart-javascript-vue-web.git

The repository contains:

  • fusionauth-backend, a preconfigured version of FusionAuth
  • vue-frontend-steps, a runnable version of each development step of the Vue application

Navigate to fusionauth-quickstart-javascript-vue-web/fusionauth-backend:

$ cd fusionauth-quickstart-javascript-vue-web/fusionauth-backend

Open your container management tool (Docker Desktop, OrbStack, or Podman) to start the Docker daemon.

To start a local instance of FusionAuth, run the following command:

$ docker compose up -d

If you see an error that reads "Is the docker daemon running?", make sure your container management tool is accepting commands. Depending on your tool:

  • to use Docker Desktop, Docker Desktop must be open
  • to use Orbstack, enable OrbStack to run as the docker daemon with docker context use orbstack, then open the Orbstack app
  • to use Podman, replace docker in the above command with podman
Note

During the Docker compose process, the included kickstart/kickstart.json file uses the FusionAuth API to:

  • Generate an API key
  • Configure CORSA browser security mechanism that lets a web page request restricted resources from another domain when the server allows the request. (Settings -> System -> CORS )
  • Create your app ("Quick Start App") with appropriate settings and redirect URIs (Applications -> Edit Application )
  • Create an admin user (admin@example.com) with access to the FusionAuth Admin UI (Users )
  • Create a user (richard@example.com) and register the user with your app
  • Create a custom theme ("Quick Start Theme") using fusionauth-backend/kickstart/css/styles.css and apply it to your default tenantThe Tenant that FusionAuth creates during installation. You can't delete the Default Tenant, which hosts the FusionAuth Admin UI Application. (Customizations -> Themes )

Once Docker compose completes, open a browser window and navigate to the Admin UI of your FusionAuth instance at http://localhost:9011/admin. Use the following admin account credentials to log in:

  • Username: admin@example.com
  • Password: password

After authenticating, you should see the FusionAuth Admin UI, which shows information about active users, logins, registrations, and more:

The FusionAuth Admin UI.

Create the Vue App#

First, create a new TypeScript Vue app with the official create-vue scaffolding tool:

  1. If your terminal is still in the fusionauth-backend directory, run cd .. to navigate back up to fusionauth-quickstart-javascript-vue-web.

  2. To generate a new Vue app with Vue Router in a folder called app-quickstart-vue, run the following command:

    $ npm create vue@3.24.0 app-quickstart-vue -- --ts --router --default
    

    Select Yes to install the create-vue package if prompted.

  3. Navigate into the app folder and install the project dependencies with the following commands:

    $ cd app-quickstart-vue
    
    $ npm install
    
  4. Delete the example components, assets, and about page that create-vue generates, as you'll replace them with your own pages:

    $ rm -rf src/components src/assets src/views/AboutView.vue
    

Customize the Vue App#

Update the Main App File#

Replace the contents of src/main.ts with the following code:

import './App.css'

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)

app.use(router)

app.mount('#app')

This file creates the Vue app, adds the router, loads the stylesheet, and mounts the app into the #app element in index.html.

Update the Root Component#

Replace the contents of src/App.vue with the following code:

<script setup lang="ts">
import { RouterView } from 'vue-router'
</script>

<template>
  <RouterView />
</template>

RouterView displays the page that matches the current URL.

Update the Router#

Replace the contents of src/router/index.ts with the following code:

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AccountView from '../views/AccountView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', name: 'home', component: HomeView },
    { path: '/account', name: 'account', component: AccountView },
    { path: '/:pathMatch(.*)*', redirect: '/' },
  ],
})

export default router

The app has two pages: a public homepage at / and an account page at /account. Any other URL redirects to the homepage.

Create the Homepage#

Replace the contents of src/views/HomeView.vue with the following code:

<script setup lang="ts">
import { useRouter } from 'vue-router'

const router = useRouter()
</script>

<template>
  <div>
    <div class="titlebar">
      <button class="button" @click="router.push('/account')">Login</button>
    </div>
    <div class="centerContainer">
      <div>Log in to request your information</div>
    </div>
  </div>
</template>

The login button redirects the user to the account page. You'll replace this click handler when you add authentication.

Create the Account Page#

Create the file src/views/AccountView.vue for the account page and add the following code:

<script setup lang="ts">
import { useRouter } from 'vue-router'

const router = useRouter()
</script>

<template>
  <div>
    <div class="titlebar">
      <button class="button" @click="router.push('/')">Logout</button>
    </div>
    <div class="centerContainer">
      <p>Your note will display here</p>
    </div>
  </div>
</template>

The logout button redirects to the homepage. You'll replace this click handler when you add authentication.

Add the Stylesheet#

Create the file src/App.css and add the following CSS:

* {
  color: #1e293b;
  font-family: Inter, Arial, Helvetica, sans-serif;
  font-size: 14px;
  margin: 0;
  padding: 0;
}

.white { color: white}

.centerContainer {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.titlebar {
  background-color: #1e293b;
  margin: 0 0 36px 0;
  min-height: 100px;
  color: #f8fafc;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.button {
  cursor: pointer;
  font-family: inherit;
  border-radius: 4px;
  padding: 10px 16px;
  margin: 16px;
  height: 40px;
  background-color: #f58320;
  border: none;
  color: white;
  transition: background .2s ease-in-out;
}
.button:hover {
  background-color: #ea580c;
  color: white;
  transition: background .2s ease-in-out;
}
.button:disabled {
  background-color: #1e293b;
  color: #64748b;
}

h2 {
  font-size: 18px;
  margin-bottom: 16px;
}

.note {
  width: 400px;
  height: 160px;
  padding: 10px;
  border: 1px solid #cbd5e1;
  border-radius: 4px;
}

Run the Vue App#

Run your app on port 3000:

  1. In package.json, update the dev script to use port 3000. Replace:

    "dev": "vite",
    

    with:

    "dev": "vite --port 3000",
    
  2. From the Vue app directory, run the following command to start the web server:

    $ npm run dev
    
  3. To view your app, open a web browser and navigate to http://localhost:3000.

Add FusionAuth for Authentication#

In this section, you protect the account page with a login.

Configure and Enable FusionAuth#

  1. From the Vue app directory (app-quickstart-vue), run the following command to install the FusionAuth Vue SDK:

    $ npm install @fusionauth/vue-sdk@~1.4.0
    
  2. Open src/main.ts and replace the file contents with the following code to:

    • import the FusionAuth Vue plugin and its configuration type
    • configure and add the FusionAuth plugin
    • send the user to the account page after they log in
    import './App.css'
    
    import { createApp } from 'vue'
    import App from './App.vue'
    import router from './router'
    import FusionAuthVuePlugin, { type FusionAuthConfig } from '@fusionauth/vue-sdk'
    
    const fusionAuthConfig: FusionAuthConfig = {
      redirectUri: 'http://localhost:3000',
      postLogoutRedirectUri: 'http://localhost:3000',
      shouldAutoRefresh: true,
      shouldAutoFetchUserInfo: true,
      scope: 'openid email profile offline_access',
      clientId: 'e9fdb985-9173-4e01-9d73-ac2d60d1dc8e',
      serverUrl: 'http://localhost:9011',
      // send users to their account page once the login redirect finishes
      onRedirect: () => { router.isReady().then(() => router.push('/account')) },
    }
    
    const app = createApp(App)
    
    app.use(FusionAuthVuePlugin, fusionAuthConfig)
    app.use(router)
    
    app.mount('#app')
Note

This FusionAuth configuration specifies the following values:

  • redirectUri: URI to open after a successful login.
  • postLogoutRedirectUri: URI to open after logout.
  • shouldAutoRefresh: Set to automatically renew the access token.
  • shouldAutoFetchUserInfo: Return data for the user as part of a successful login.
  • scope: OAuth 2.0 permissions for the access token.
  • clientId: ID of the application in the FusionAuth instance.
  • serverUrl: Base URL for the FusionAuth authorization server.
  • onRedirect: Callback that executes when a redirect occurs. The SDK calls it before the router has loaded the first page, so it waits for router.isReady() before navigating.

Protect the Account Page#

Open src/router/index.ts and replace the file contents with the following code to add a beforeEnter guard to the account route. The guard uses the FusionAuth Vue SDK to check whether the user is logged in, and sends users who aren't logged in back to the homepage:

import { createRouter, createWebHistory } from 'vue-router'
import { useFusionAuth } from '@fusionauth/vue-sdk'
import HomeView from '../views/HomeView.vue'
import AccountView from '../views/AccountView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', name: 'home', component: HomeView },
    {
      path: '/account',
      name: 'account',
      component: AccountView,
      // send users who aren't logged in back to the home page
      beforeEnter: () => {
        if (!useFusionAuth().isLoggedIn.value) return '/'
      },
    },
    { path: '/:pathMatch(.*)*', redirect: '/' },
  ],
})

export default router

Add Login and Logout to Homepage#

Open src/views/HomeView.vue and replace the file contents with the following code to:

  • get the login state, user data, and login and logout functions from the FusionAuth Vue SDK useFusionAuth() composable
  • show an authenticated user's email and a logout button in the title bar, otherwise a login button
  • start the login process with the SDK login() function when the user clicks the login button
<script setup lang="ts">
import { useFusionAuth } from '@fusionauth/vue-sdk'

const { isLoggedIn, userInfo, login, logout } = useFusionAuth()
</script>

<template>
  <div>
    <div class="titlebar">
      <template v-if="isLoggedIn">
        <span class="white">{{ userInfo?.email }}</span>
        <button class="button" @click="logout()">Logout</button>
      </template>
      <button v-else class="button" @click="login()">Login</button>
    </div>
    <div class="centerContainer">
      <div>Log in to request your information</div>
    </div>
  </div>
</template>

Add Logout to Account Page#

Open src/views/AccountView.vue and replace the file contents with the following code to:

  • get user data and the logout function from the FusionAuth Vue SDK
  • show the page once the SDK has fetched the user's data
  • display the user's email in the title bar
  • start the logout process with the SDK logout() function when the user clicks the logout button
<script setup lang="ts">
import { useFusionAuth } from '@fusionauth/vue-sdk'

const { isGettingUserInfo, userInfo, logout } = useFusionAuth()
</script>

<template>
  <div v-if="!isGettingUserInfo">
    <div class="titlebar">
      <span class="white">{{ userInfo?.email }}</span>
      <button class="button" @click="logout()">Logout</button>
    </div>
    <div class="centerContainer">
      <p>Your note will display here</p>
    </div>
  </div>
</template>

Test Authentication#

  1. Start the web server:

    $ npm run dev
    
  2. Open a private browser window so you don't retain your login status from previous sections.

  3. Navigate to the Vue app at http://localhost:3000.

    The landing page of the Vue app.

    The landing page of the Vue app.

  4. Click the login button. Your browser should redirect to FusionAuth at http://localhost:9011.

    The FusionAuth login screen.
  5. Authenticate with the credentials for the user created in the fusionauth-backend/kickstart/kickstart.json file:

    • Username: richard@example.com
    • Password: password

FusionAuth validates the credentials, then redirects back to the redirectUri set in src/main.ts. The onRedirect callback then navigates to the account page.

Right now, you should see an account page with your email and a logout button in the title bar, and the placeholder text Your note will display here:

The account page, showing placeholder text.

The account page, showing placeholder text.

Next, you'll replace the placeholder with a note for each user.

Add a Note for Each User#

FusionAuth gives every user a unique Id. In this section, you use that Id to keep a separate note for each user.

Update the Account Page#

Open src/views/AccountView.vue and replace the file contents with the following code to:

  • read the user's Id from userInfo.sub, which the SDK fetched from FusionAuth after login
  • load the user's saved note, or start a new note with a greeting
  • save the note under a key that contains the user's Id
<script setup lang="ts">
import { ref, watch } from 'vue'
import { useFusionAuth } from '@fusionauth/vue-sdk'

const { isGettingUserInfo, userInfo, logout } = useFusionAuth()
const note = ref('')
const saved = ref(false)

// sub is the user's FusionAuth Id, so each user gets their own note
const noteKey = () => `note-${userInfo.value?.sub}`

watch(
  userInfo,
  (info) => {
    if (info?.sub) {
      note.value = localStorage.getItem(noteKey()) ?? `Hello ${info.given_name ?? info.email}! This note is yours alone.`
    }
  },
  { immediate: true },
)

function saveNote() {
  localStorage.setItem(noteKey(), note.value)
  saved.value = true
}
</script>

<template>
  <div v-if="!isGettingUserInfo">
    <div class="titlebar">
      <span class="white">{{ userInfo?.email }}</span>
      <button class="button" @click="logout()">Logout</button>
    </div>
    <div class="centerContainer">
      <h2>Your note</h2>
      <textarea class="note" v-model="note" @input="saved = false"></textarea>
      <button class="button" @click="saveNote">Save note</button>
      <p v-if="saved">Saved</p>
    </div>
  </div>
</template>

The app saves notes in the browser's localStorage, so they stay in this browser only. A production app would save them in a database, using the same user Id to look them up.

Test the Notes#

  1. Browse to the account page at http://localhost:3000/account. The note starts with a greeting that uses your first name.

    The account page, showing Richard's note.

    The account page, showing Richard's note.

  2. Edit the note, click Save note, and reload the page. Your note is still there.

  3. Click Logout, then Login. On the FusionAuth login page, click Create an account and register a second user with any email address and password.

  4. The second user gets a new note, without Richard's text. The registration form doesn't ask for a name, so the greeting uses the email address instead. Log out and log in as richard@example.com again to see Richard's note.

Summary#

In this QuickStart, FusionAuth handled login for your Vue app:

  • The Vue SDK sent users to the FusionAuth login page and brought them back to the app after login, so the app never saw their passwords.
  • The route guard used the SDK to keep logged-out users away from the account page.
  • After login, the SDK fetched the user's details from FusionAuth, including the unique user Id that keeps each note separate.

Next Steps#

This is a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see Get Started.

FusionAuth has many features (including Social Login, Single Sign-On, Passkeys, Multi-factor Authentication), most of which are free. Some require additional licensing. For details, see the pricing page.

For information on the Vue SDK, see the Vue SDK documentation.

You can ask general questions in the FusionAuth forum.