Skip to content

ZerNico/nuxt-logto

Repository files navigation

Nuxt Logto

npm version npm downloads License Nuxt

Logto auth module for Nuxt 3.

Quick Setup

  1. Add @zernico/nuxt-logto dependency to your project
# Using pnpm
pnpm add @zernico/nuxt-logto

# Using yarn
yarn add @zernico/nuxt-logto

# Using npm
npm install @zernico/nuxt-logto
  1. Add @zernico/nuxt-logto to the modules section of nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@zernico/nuxt-logto'],
})
  1. Configure it:
export default defineNuxtConfig({
  modules: ['@zernico/nuxt-logto'],
  logto: {
    appId: '<your-application-id>',
    appSecret: '<your-app-secret-copied-from-console>',
    endpoint: '<your-logto-endpoint>', // E.g. http://localhost:3001
    origin: '<your-nextjs-app-origin>', // E.g. http://localhost:3000
    basePath: '/api/logto', // Path to your logto api routes, e.g. /api/logto
    cookieSecret: 'complex_password_at_least_32_characters_long',
    cookieSecure: process.env.NODE_ENV === 'production',
    resources: ['<your-resource-id>'], // optionally add a resource
  },
})
  1. Add the api routes
// lib/logto.ts
import { LogtoClient } from "#logto";

export const logtoClient = new LogtoClient()
// server/api/logto/[action].ts
import { logtoClient } from '~/lib/logto'

export default logtoClient.handleAuthRoutes()
  1. Optional configuration
// server/api/logto/[action].ts
import { logtoClient } from '~/lib/logto'

export default logtoClient.handleAuthRoutes({
  getAccessToken: true, // get access token from logto
  resource: '<your-resource-id>', // optionally add a resource for your access token
  fetchUserInfo: true, // fetch user info from logto, in most cases you want to use claims instead
})
  1. Use the composable
<script setup lang="ts">
const { signIn, signOut } = useLogto();
</script>

<template>
  <div>
    <button @click="() => signIn()">Login</button>
    <button @click="() => signOut()">Logout</button>
  </div>
</template>

That's it! You can now use Nuxt Logto in your Nuxt app ✨

Development

# Install dependencies
pnpm install

# Generate type stubs
pnpm run dev:prepare

# Develop with the playground
pnpm run dev

# Build the playground
pnpm run dev:build

# Run ESLint
pnpm run lint

# Run Vitest
pnpm run test
pnpm run test:watch

# Release new version
npm run release