Giter Club home page Giter Club logo

nuxt-auth-utils's Introduction

Nuxt Auth Utils

npm version npm downloads License Nuxt

Minimalist Authentication module for Nuxt exposing Vue composables and server utils.

Features

Requirements

This module only works with SSR (server-side rendering) enabled as it uses server API routes. You cannot use this module with nuxt generate.

Quick Setup

  1. Add nuxt-auth-utils dependency to your project
# Using pnpm
pnpm add -D nuxt-auth-utils

# Using yarn
yarn add --dev nuxt-auth-utils

# Using npm
npm install --save-dev nuxt-auth-utils
  1. Add nuxt-auth-utils to the modules section of nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    'nuxt-auth-utils'
  ]
})
  1. Add a NUXT_SESSION_PASSWORD env variable with at least 32 characters in the .env.
# .env
NUXT_SESSION_PASSWORD=password-with-at-least-32-characters

Nuxt Auth Utils can generate one for you when running Nuxt in development the first time when no NUXT_SESSION_PASSWORD is set.

  1. That's it! You can now add authentication to your Nuxt app โœจ

Vue Composables

Nuxt Auth Utils automatically adds some plugins to fetch the current user session to let you access it from your Vue components.

User Session

<script setup>
const { loggedIn, user, session, clear } = useUserSession()
</script>

<template>
  <div v-if="loggedIn">
    <h1>Welcome {{ user.login }}!</h1>
    <p>Logged in since {{ session.loggedInAt }}</p>
    <button @click="clear">Logout</button>
  </div>
  <div v-else>
    <h1>Not logged in</h1>
    <a href="/api/auth/github">Login with GitHub</a>
  </div>
</template>

Server Utils

The following helpers are auto-imported in your server/ directory.

Session Management

// Set a user session, note that this data is encrypted in the cookie but can be decrypted with an API call
// Only store the data that allow you to recognize an user, but do not store sensitive data
await setUserSession(event, {
  user: {
    // ... user data
  },
  loggedInAt: new Date()
  // Any extra fields
})

// Get the current user session
const session = await getUserSession(event)

// Clear the current user session
await clearUserSession(event)

// Require a user session (send back 401 if no `user` key in session)
const session = await requireUserSession(event)

You can define the type for your user session by creating a type declaration file (for example, auth.d.ts) in your project to augment the UserSession type:

declare module '#auth-utils' {
  interface UserSession {
    // define the type here
  }
}
export {}

OAuth Event Handlers

All helpers are exposed from the oauth global variable and can be used in your server routes or API routes.

The pattern is oauth.<provider>EventHandler({ onSuccess, config?, onError? }), example: oauth.githubEventHandler.

The helper returns an event handler that automatically redirects to the provider authorization page and then call onSuccess or onError depending on the result.

The config can be defined directly from the runtimeConfig in your nuxt.config.ts:

export default defineNuxtConfig({
  runtimeConfig: {
    oauth: {
      <provider>: {
        clientId: '...',
        clientSecret: '...'
      }
    }
  }
})

It can also be set using environment variables:

  • NUXT_OAUTH_<PROVIDER>_CLIENT_ID
  • NUXT_OAUTH_<PROVIDER>_CLIENT_SECRET

Supported OAuth Providers

  • Auth0
  • Discord
  • GitHub
  • Google
  • Spotify
  • Twitch
  • Battle.net

You can add your favorite provider by creating a new file in src/runtime/server/lib/oauth/.

Example

Example: ~/server/routes/auth/github.get.ts

export default oauth.githubEventHandler({
  config: {
    emailRequired: true
  },
  async onSuccess(event, { user, tokens }) {
    await setUserSession(event, {
      user: {
        githubId: user.id
      }
    })
    return sendRedirect(event, '/')
  },
  // Optional, will return a json error and 401 status code by default
  onError(event, error) {
    console.error('GitHub OAuth error:', error)
    return sendRedirect(event, '/')
  },
})

Make sure to set the callback URL in your OAuth app settings as <your-domain>/auth/github.

Development

# Install dependencies
npm install

# Generate type stubs
npm run dev:prepare

# Develop with the playground
npm run dev

# Build the playground
npm run dev:build

# Run ESLint
npm run lint

# Run Vitest
npm run test
npm run test:watch

# Release new version
npm run release

nuxt-auth-utils's People

Contributors

atinux avatar danielroe avatar ahmedrangel avatar aksharahegde avatar azurency avatar arashsheyda avatar gerbuuun avatar samulefevre avatar sifferhans avatar berzinsu avatar justserdar avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.