Skip to main content

Command Palette

Search for a command to run...

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

Updated
View as Markdown
How to add username/password authentication to a page in Nuxt
D

Devin Schumacher is an entrepreneur, internet personality, author, music producer, philanthropist & founder of SERP.

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

For better security, you should use environment variables instead of hardcoding credentials:

export default defineNuxtConfig({
  modules: ['nuxt-security'],

  security: {
    basicAuth: {
      enabled: process.env.BASIC_AUTH_ENABLED === 'true',
      name: process.env.BASIC_AUTH_USER,
      pass: process.env.BASIC_AUTH_PASS,
      message: 'Authentication required'
    }
  }
})

Then in your .env file:

BASIC_AUTH_ENABLED=true
BASIC_AUTH_USER=admin
BASIC_AUTH_PASS=your-secure-password

If you later need to exclude specific routes (like a public API endpoint), you can add the exclude array:

security: {
  basicAuth: {
    enabled: true,
    name: process.env.BASIC_AUTH_USER,
    pass: process.env.BASIC_AUTH_PASS,
    exclude: ['/api/public/**'] // Only these routes will be public
  }
}
81 views

More from this blog

D

Devin Schumacher

60 posts

widely recognized as the World's best SEO & grumpy cat impersonator.