npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@inkbird-io/nuxt-auth-utils

v0.0.32

Published

Minimalist Auth module for Nuxt with SSR

Downloads

3

Readme

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 in your Nuxt project
npx nuxi@latest module add 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 generates one for you when running Nuxt in development the first time if 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="/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 a user, but do not store sensitive data
// Merges new data with existing data using defu()
await setUserSession(event, {
  user: {
    // ... user data
  },
  loggedInAt: new Date()
  // Any extra fields
})

// Replace a user session. Same behaviour as setUserSession, except it does not merge data with existing data
await replaceUserSession(event, data)

// 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:

// auth.d.ts
declare module '#auth-utils' {
  interface User {
    // Add your own fields
  }

  interface UserSession {
    // Add your own fields
  }
}

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 calls 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
  • AWS Cognito
  • Battle.net
  • Discord
  • Facebook
  • GitHub
  • Google
  • Keycloak
  • LinkedIn
  • Microsoft
  • Spotify
  • Twitch

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.

Extend Session

We leverage hooks to let you extend the session data with your own data or log when the user clears the session.

// server/plugins/session.ts
export default defineNitroPlugin(() => {
  // Called when the session is fetched during SSR for the Vue composable (/api/_auth/session)
  // Or when we call useUserSession().fetch()
  sessionHooks.hook('fetch', async (session, event) => {
    // extend User Session by calling your database
    // or
    // throw createError({ ... }) if session is invalid for example
  })

  // Called when we call useServerSession().clear() or clearUserSession(event)
  sessionHooks.hook('clear', async (session, event) => {
    // Log that user logged out
  })
})

Configuration

We leverage runtimeConfig.session to give the defaults option to h3 useSession.

You can overwrite the options in your nuxt.config.ts:

export default defineNuxtConfig({
  modules: ['nuxt-auth-utils'],
  runtimeConfig: {
    session: {
      maxAge: 60 * 60 * 24 * 7 // 1 week
    }
  }
})

Our defaults are:

{
  name: 'nuxt-session',
  password: process.env.NUXT_SESSION_PASSWORD || '',
  cookie: {
    sameSite: 'lax'
  }
}

Checkout the SessionConfig for all options.

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