Build Nuxt authentication with Logto
Tags: nuxt, webdev, programming, opensource
Published: 2024-05-27 06:34:29

Learn how to build a user authentication flow with Nuxt by integrating Logto SDK.

---
# Get started
### Introduction

- [Logto](https://logto.io/) is an open-source Auth0 alternative for building identity infrastructures. It supports various sign-in methods, including username, email, phone number, and popular social sign-ins like Google and GitHub.
- [Nuxt](https://nuxt.com/) an open source framework that makes web development intuitive and powerful.

In this tutorial, we will show you how to build a user authentication flow with Nuxt by integrating Logto SDK. The tutorial uses TypeScript as the programming language.

### Prerequisites
Before you begin, ensure you have the following:

- A Logto account. If you don't have one, you can [sign up for free](https://auth.logto.io/sign-in).
- A Nuxt development environment and a project.

### Create a Logto application
To get started, create a Logto application with the "Traditional web" type. Follow these steps to create a Logto application:

1. Sign in to the [Logto Console](https://auth.logto.io/sign-in).
2. In the left navigation bar, click on **Applications**.
3. Click on **Create application**.
4. In the opened page, find the "Traditional web" section and locate the "Nuxt" card.
5. Click on **Start building**, and input the name of your application.
6. Click on **Create**.

Then you should see an interactive tutorial that guides you through the process of integrating Logto SDK with your Nuxt application. The following content can be a reference for future use.

{% cta http://cloud.logto.io/?sign_up=true %} Try Logto Cloud's interactive tutorial {% endcta %}

# Integrate Logto SDK
### Installation
Install Logto SDK via your favorite package manager:

```
# or pnpm, yarn, etc.
npm i @logto/nuxt
```

### Register Logto module

In your Nuxt config file (`nuxt.config.ts`), add the Logto module:

```
export default defineNuxtConfig({
  modules: ['@logto/nuxt'],
  // ...other configurations
});
```
The minimal configuration for the module is as follows:

```
export default defineNuxtConfig({
  modules: ['@logto/nuxt'],
  runtimeConfig: {
    logto: {
      endpoint: '<your-logto-endpoint>',
      appId: '<your-logto-app-id>',
      appSecret: '<your-logto-app-secret>',
      cookieEncryptionKey: '<a-random-string>',
    },
  },
  // ...other configurations
});
```
Since these information are sensitive, it's recommended to use environment variables:

```
# .env file
NUXT_LOGTO_ENDPOINT="<your-logto-endpoint>"
NUXT_LOGTO_APP_ID="<your-logto-app-id>"
NUXT_LOGTO_APP_SECRET="<your-logto-app-secret>"
NUXT_LOGTO_COOKIE_ENCRYPTION_KEY="<a-random-string>"
```

See [runtime config](https://nuxt.com/docs/guide/going-further/runtime-config) for more information.

### Implement sign-in and sign-out

> In the following code snippets, we assume your app is running on http://localhost:3000/.

### Configure redirect URIs
Switch to the application details page of Logto Console. Add a Redirect URI http://localhost:3000/callback.

[Redirect URI](https://www.oauth.com/oauth2-servers/redirect-uris/) is an OAuth 2.0 concept which implies the location should redirect after authentication.
Similarly, add http://localhost:3000/ to the "Post sign-out redirect URI" section.

[Post Sign-out Redirect URI](https://openid.net/specs/openid-connect-rpinitiated-1_0.html#RPLogout) is an OAuth 2.0 concept which implies the location should redirect after signing out.

Then click "Save" to save the changes.

When registering `@logto/nuxt` module, it will do the following:

- Add three routes for sign-in (`/sign-in`), sign-out (`/sign-out`), and callback (`/callback`).
- Import two composables: `useLogtoClient` and `useLogtoUser`.

These routes are configurable via `logto.pathnames` in the module options, for example:

```
export default defineNuxtConfig({
  logto: {
    pathnames: {
      signIn: '/login',
      signOut: '/logout',
      callback: '/auth/callback',
    },
  },
  // ...other configurations
});
```

Check out the [type definition file](https://github.com/logto-io/js/blob/HEAD/packages/nuxt/src/runtime/utils/types.ts) in the `@logto/nuxt` package for more information.

Since Nuxt pages will be hydrated and become a single-page application (SPA) after the initial load, we need to redirect the user to the sign-in or sign-out route when needed.

```
<a :href="/sign-in">Sign in</a>
<br />
<a :href="/sign-out">Sign out</a>
```

### Display user information
To display the user's information, you can use the `useLogtoUser()` composable, which is availble on both server and client side:

```
<script setup lang="ts">
  const user = useLogtoUser();
</script>
<template>
  <ul v-if="Boolean(user)">
    <li v-for="(value, key) in user"><b>{{ key }}:</b> {{ value }}</li>
  </ul>
  <!-- Simplified button for sign-in and sign-out -->
  <a :href="`/sign-${ user ? 'out' : 'in' }`"> Sign {{ user ? 'out' : 'in' }} </a>
</template>
```

# Checkpoint: Run the application
Now you can run the application and try to sign-in/sign-out with Logto:

1. Open the application in your browser, you should see the "Sign in" button.
2. Click the "Sign in" button, and you should be redirected to the Logto sign-in page.
3. After you have signed in, you should be redirected back to the application, and you should see the user data and the "Sign out" button.
4. Click the "Sign out" button, and you should be redirected to the Logto sign-out page, and then redirected back to the application with an unsigned-in state.

If you encounter any issues during the integration, please don't hesitate to [join our Discord server](https://discord.com/invite/UEPaF3j5e6) to chat with the community and the Logto team!

# Further readings

- [Customize sign-in experience](https://docs.logto.io/docs/recipes/customize-sie/)

{% cta https://logto.io/?ref=dev %} Try Logto Cloud for free {% endcta %}