Ref
- Nuxt auth
Setup
- Add
nuxt-auth
and axios
:
1 2
| yarn add --exact @nuxtjs/auth-next yarn add @nuxtjs/axios
|
- Config
nuxt.config.js
:
1 2 3 4 5 6 7 8 9
| { modules: [ '@nuxtjs/axios', '@nuxtjs/auth-next' ], auth: { } }
|
- If using Typescript, add
@nuxtjs/auth-next
to tsconfig.json
:
1 2 3 4 5 6 7
| { compilerOptions: { "types": [ "@nuxtjs/auth-next", ] }, }
|
- Add auth to route:
- Per route, add to
.vue
file for a page:
1 2 3
| export default { middleware: 'auth' }
|
- Global, add to
nuxt.config.js
:
1 2 3
| router: { middleware: ['auth'] }
|
To bypass auth for some route, add to .vue
file for a page:
1 2 3
| export default { auth: false }
|
To redirect to /
instead of stay in the url after a successful login, add this to .vue
for a page:
1 2 3
| export default { auth: 'guest' }
|
- Scheme
- Schemes define authentication logic.
- Strategy is a scheme instance.
- Multiple strategies can be applied to a nuxt app.
Here’s the config for local
and github
strategy in nuxt.config.js
:
1 2 3 4 5 6
| auth: { strategies: { local: { }, github: { }, } }
|
Here we only consider local scheme.
- Local scheme is crendentials/token based for flows like ‘JWT’.
- Local scheme is enabled, preconfigured and default. Can be turned off by setting
strategies.local: false
.
Config in nuxt.config.js
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| auth: { strategies: { local: { token: { property: 'token', global: true }, user: { property: 'user' }, endpoints: { login: { url: '/login', method: 'post'}, logout: false, user: { url: '/me', method: 'get' } } } } }
|
Next, add index.js
in store
folder to activate vuex store.