Add Login to a Vue App with the FusionAuth Vue SDK

On this page

The Vue SDK adds login, registration, and logout to a Vue application, and tracks whether the user is logged in. To build a complete application step by step, see the Vue QuickStart.

The SDK sends users to the FusionAuth hosted login pages, which you can style with a theme. After login, FusionAuth sends users back to your Vue application.

By default, the SDK uses the hosted backend on your FusionAuth instance, so your application needs no server code. The hosted backend exchanges the authorization code for tokens and stores the tokens in HttpOnly cookiesA cookie that the browser sends with requests but hides from JavaScript, so a cross-site scripting attack can't read the cookie.:

  • app.at holds the access token. Your APIs read the access token to authorize requests.
  • app.rt holds the refresh token. The SDK uses the refresh token to get a new access token.

To run the token exchange on your own server instead, see Use Your Own Backend. To keep tokens in the browser and bind the tokens to a key, use DPoP mode.

Prerequisites#

  • FusionAuth 1.45.0 or later, which adds the hosted backend.
  • A FusionAuth ApplicationA software program that your users log in to through FusionAuth.. On the OAuth tab of the Application, add the URL that FusionAuth returns users to after login to Authorized redirect URLs. The SDK calls this URL redirectUri.
  • CORSA browser security mechanism that lets a web page request restricted resources from another domain when the server allows the request. that accepts requests from your application. Under Settings -> System -> CORS , enable Include credentials in CORS requests, add the origin of your application to Allowed origins, and allow the GET and POST methods. The SDK sends the token cookies with each request to FusionAuth, so FusionAuth must accept credentials from your origin.
  • Vue 3.5.0 or later.
FusionAuth Cloud blocks cross-site hosted backend requests

When developing against a FusionAuth Cloud instance with a hostname ending in fusionauth.io, requests from applications outside the fusionauth.io domain fail with a 403 status code.

These endpoints do not work correctly for cross-site requests. A cross-site request comes from an application on a different registrable domain than FusionAuth. For example, requests from app.acme.com to acme.fusionauth.io are cross-site.

If possible, have FusionAuth and your application served by the same domain, using a proxy if needed. For example, serve your app from app.acme.com and FusionAuth from auth.acme.com.

If this configuration is not possible, use one of these alternative methods:

Modifying FusionAuth CORS configuration options does not fix this issue because the cookies that FusionAuth writes will not be accessible cross domain.

Add Login to Your Application#

  1. Install the SDK:

    $ npm install @fusionauth/vue-sdk
    
  2. Install FusionAuthVuePlugin when you create your Vue application. Set clientId to the client Id of your FusionAuth Application, serverUrl to the URL of your FusionAuth instance, and redirectUri to the URL you added to Authorized redirect URLs:

    import { createApp } from 'vue';
    import FusionAuthVuePlugin, { type FusionAuthConfig } from '@fusionauth/vue-sdk';
    import App from './App.vue';
    
    const config: FusionAuthConfig = {
      clientId: 'e9fdb985-9173-4e01-9d73-ac2d60d1dc8e',
      serverUrl: 'http://localhost:9011',
      redirectUri: 'http://localhost:5173',
      shouldAutoFetchUserInfo: true,
      shouldAutoRefresh: true,
    };
    
    const app = createApp(App);
    app.use(FusionAuthVuePlugin, config);
    app.mount('#app');
    

    shouldAutoFetchUserInfo loads the user's profile after login, and shouldAutoRefresh refreshes the access token before the token expires. For every option, see Web SDK Configuration.

  3. Call the useFusionAuth composable in a component to add login, registration, and logout buttons:

    <script setup lang="ts">
    import { useFusionAuth } from '@fusionauth/vue-sdk';
    
    const {
      isLoggedIn,
      isGettingUserInfo,
      userInfo,
      login,
      register,
      logout,
    } = useFusionAuth();
    </script>
    
    <template>
      <p v-if="isGettingUserInfo">Loading...</p>
    
      <div v-else-if="isLoggedIn">
        <p v-if="userInfo?.given_name">Welcome {{ userInfo.given_name }}!</p>
        <button @click="logout()">Log Out</button>
      </div>
    
      <div v-else>
        <button @click="login()">Log In</button>
        <button @click="register()">Register</button>
      </div>
    </template>
    

    login and register send the browser to the FusionAuth login and registration pages. logout ends the session and returns the browser to redirectUri. To return users to a different page after logout, set postLogoutRedirectUri and add the URL to Authorized redirect URLs.

  4. Start your application and click Log In . The browser opens the FusionAuth login page. After you log in, FusionAuth returns you to your application, and the component shows Log Out .

For every value that useFusionAuth returns, see the useFusionAuth reference.

Use the Pre-Built Buttons#

Instead of writing your own buttons, use the styled buttons from the SDK. The plugin registers the buttons globally, so you don't import the buttons in each component. Import the button styles once, next to the plugin:

import '@fusionauth/vue-sdk/dist/style.css';

Then place the buttons in any template. Set the CSS variables to match the buttons to your design:

<template>
  <FusionAuthLoginButton />
  <FusionAuthRegisterButton />
  <FusionAuthLogoutButton />
</template>

<style>
  :root {
    --fusionauth-button-background-color: #096324;
    --fusionauth-button-text-color: #fff;
  }
</style>

Show Content by Login State and Role#

Wrap content in RequireAuth to show the content only to logged-in users. Set with-role to a role name, or to an array of role names, to require at least one of the roles. Wrap content in RequireAnonymous to show the content only to logged-out users:

<template>
  <RequireAuth :with-role="['admin', 'editor']">
    <button>Delete User</button>
  </RequireAuth>
  <RequireAnonymous>
    <p>Log in to manage users.</p>
  </RequireAnonymous>
</template>

RequireAuth reads the user's profile, and shows nothing until the profile loads. Set shouldAutoFetchUserInfo to true, or call getUserInfo from useFusionAuth.

These components only change what the browser shows. Check the access token on your server before you return protected data.

Return Users to a Page After Login#

To return users to the page they started from, pass a string to login or register. The SDK passes the string to the onRedirect function when the browser returns from FusionAuth:

const config: FusionAuthConfig = {
  // ...
  onRedirect: (state?: string) => {
    if (state) router.push(state);
  },
};
login(router.currentRoute.value.fullPath);

The pre-built login and register buttons accept the same string in the state prop.

Use the SDK with Nuxt#

To read the token cookies during server rendering in Nuxt, pass the Nuxt useCookie composable as nuxtUseCookie in a Nuxt plugin:

import { useCookie } from '#app';
import FusionAuthVuePlugin from '@fusionauth/vue-sdk';

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(FusionAuthVuePlugin, {
    ...config,
    nuxtUseCookie: useCookie,
  });
});

To reach the SDK outside components, such as in route middleware, create the SDK instance with createFusionAuth. Pass the instance to the plugin, and provide the instance to the rest of the Nuxt application:

import { useCookie } from '#app';
import FusionAuthVuePlugin, { createFusionAuth } from '@fusionauth/vue-sdk';

export default defineNuxtPlugin({
  setup(nuxtApp) {
    const fusionauth = createFusionAuth({ ...config, nuxtUseCookie: useCookie });
    nuxtApp.vueApp.use(FusionAuthVuePlugin, { instance: fusionauth });
    return {
      provide: { fusionauth },
    };
  },
});

Call APIs in DPoP Mode#

In DPoPAn OAuth 2.0 extension that ties access and refresh tokens to a key pair that the client holds. A stolen token doesn't work without the private key. mode, the SDK calls FusionAuth directly instead of the hosted backend, and binds each token to a key that the browser generates. A stolen DPoP token doesn't work without the key. DPoP mode requires Vue SDK 1.4.0 and FusionAuth 1.63.0 or later. To configure FusionAuth for DPoP, see Use DPoP in a Browser App.

To enable DPoP mode, set useDpop to true:

const config: FusionAuthConfig = {
  clientId: 'e9fdb985-9173-4e01-9d73-ac2d60d1dc8e',
  serverUrl: 'http://localhost:9011',
  redirectUri: 'http://localhost:5173',
  useDpop: true,
  dpopTokenStorage: 'localStorage',
  onRedirect: () => router.push('/account'),
};

With localStorage, the user stays logged in across page reloads. With memory, a reload logs the user out.

In DPoP mode, the SDK finishes login in the browser after the redirect. The SDK calls onRedirect after isLoggedIn and the tokens update, so navigate after login in onRedirect.

In DPoP mode, useFusionAuth also returns dpopFetch, generateProof, and getAccessToken. Call dpopFetch like fetch. dpopFetch adds the DPoP headers and retries when the server asks for a new nonce:

const { dpopFetch, generateProof, getAccessToken } = useFusionAuth();

const response = await dpopFetch('https://api.example.com/data', { method: 'GET' });

When you use an HTTP library such as axios, build the headers with getAccessToken and generateProof:

const accessToken = getAccessToken();
const proof = await generateProof('https://api.example.com/data', 'GET', accessToken);

await axios.get('https://api.example.com/data', {
  headers: { Authorization: `DPoP ${accessToken}`, DPoP: proof },
});

The three functions are undefined when useDpop is false.