Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save devinschumacher/84ba661b7d1c32660ccfb82f00b2c863 to your computer and use it in GitHub Desktop.
Save devinschumacher/84ba661b7d1c32660ccfb82f00b2c863 to your computer and use it in GitHub Desktop.
How to add username/password authentication to a page in Nuxt

How to add username/password authentication to a page in Nuxt





nuxt-security provides middleware to easily add login/pass authentication to any route in Nuxt via Basic Auth.

Only users with correct credentials passed to the browser prompt will be able to see the application. Others will be automatically rejected.

This middleware is disabled by default. You can enable it globally like following:

  1. Install nuxt-security
  2. Enable basic auth in nuxt.config.ts
export default defineNuxtConfig({
  security: {
    basicAuth: {
      // options
    }
  }
})

Basic Auth accepts following configuration options:

type BasicAuth = {
  exclude?: string[];
  include?: string[]; // Paths to include in Basic Auth functionality.
  name: string; // User name that is required for user/pass flow
  pass: string; // User password that is required for user/pass flow
  enabled: boolean; // Boolean value to indicate whether a BasicAuth is enabled or not.
  message: string;
}

Example

Let's say you want to password protect a page on your website site.com/clients-i-hate

export default defineNuxtConfig({
  security: {
    basicAuth: {
      include: '/clients-i-hate',
      name: 'youLoginUsername',
      pass: 'thePasswordYouChose',
      enabled: 'true',
    }
  }
})

And when a visitor tries to reach the page, they will get this:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment