authjs
-provider.NuxtAuthHandler
After following the quick-start setup and then optionally diving even deeper into the nuxt-auth
config inside your nuxt.config.ts
you can begin defining providers and other options inside your NuxtAuthHandler
.
For development, using the quick-start setup will already bring you quite far. For a production deployment, you will have to additionally:
- set the
origin
by:- exporting the
AUTH_ORIGIN
-environment variable at runtime (higher precedence) - setting the
origin
-key inside thenuxt.config.ts
config at build-time (lower precendence)
- exporting the
- set a secret inside the
NuxtAuthHandler
config
Creating the NuxtAuthHandler
In order to create your own NuxtAuthHandler
, create the file ~/server/api/auth/[...].ts
. This file will automatically set up the authentication API that responds to all requests going to https://localhost/api/auth/*
. If you wish you can also use a custom file location and api path, however this change will need to be reflected in the basePath, which is configured in the nuxt.config.ts.
[...].ts
- this is a so-called "catch-all" route, read more in the Nuxt catch-all docs.Configuring the NuxtAuthHandler
After creating the file, add the NuxtAuthHandler({ ... })
to it. The NuxtAuthHandler({ ... })
is used to configure how the authentication itself behaves, what callbacks should be called, what database adapters should be used and more:
// file: ~/server/api/auth/[...].tsimport { NuxtAuthHandler } from '#auth'export default NuxtAuthHandler({ // your authentication configuration here!})
The NuxtAuthHandler
accepts all options that NextAuth.js accepts for its API initialization. Use this place to configure authentication providers (oauth-Google, credential flow, ...), your secret
, add callbacks for authentication events, configure a custom logger and more. Read the NextAuth.js
docs to see all possible options.
secret
In theory the only required configuration key for production is the secret
. You can set it directly inside the NuxtAuthHandler
. In practice however you may also want to configure at least one provider so that your users can actually login.
To avoid hard-coding of the secret you can make it configurable at runtime by using an environment variable and exporting it at runtime or by using the nuxt runtimeconfig (and then also setting the correct environment at runtime):
// file: ~/server/api/auth/[...].tsimport { NuxtAuthHandler } from '#auth'export default NuxtAuthHandler({ // A secret string you define, to ensure correct encryption - required in production secret: process.env.AUTH_SECRET // rest of your authentication configuration here!})
Further Examples
Checkout the provider recipes to see different examples of provider configurations, e.g., for Strapi or Directus.