Authentication
This module exposes composables that are auto-imported by Nuxt 3.
Configuration
When using @nuxtjs/strapi
for authentication, the user jwt token will be stored in a cookie (strapi_jwt
by default). By using the default cookie configuration, the expiration will be set to Session
, which means the cookie will disappear when the browser is closed, and users will have to log in everytime.
If you want your cookie to stay longer, we recommand to use the configuration below (expiration is set to 14 days, feel free to change it):
export default defineNuxtConfig({
strapi: {
cookie: {
path: '/',
maxAge: 14 * 24 * 60 * 60,
secure: process.env.NODE_ENV === 'production',
sameSite: true
}
}
})
useStrapiUser
Once logged in, you can access your user everywhere:
const user = useStrapiUser()
Learn how to protect your routes by writing your own auth middleware composable.
useStrapiToken
This composable is an helper to get the jwt token. It is used internally to get the strapi_jwt
cookie.
const token = useStrapiToken()
useStrapiAuth
This composable exposes all the methods available in the Strapi Users & Permissions plugin.
login
, register
, resetPassword
and authenticateProvider
methods, the user is populated through the fetchUser
method.login
Submit the user's identifier and password credentials for authentication. Sets user
and token
.
- Arguments:
- data:
StrapiAuthenticationData
- data:
- Returns:
Promise<StrapiAuthenticationResponse>
<script setup lang="ts">
const { login } = useStrapiAuth()
const router = useRouter()
const onSubmit = async () => {
try {
await login({ identifier: '', password: '' })
router.push('/authenticated-page')
} catch (e) {}
}
</script>
Check out the Strapi Login documentation.
logout
<script setup lang="ts">
const { logout } = useStrapiAuth()
const router = useRouter()
const onClick = () => {
logout()
router.push('/')
}
</script>
register
Creates a new user in the database with a default role as Authenticated
.
Custom user fields, if added to the content type, e.g. phoneNumber
, can be added to the payload as well.
- Arguments:
- data:
StrapiRegistrationData
- data:
- Returns:
Promise<StrapiAuthenticationResponse>
<script setup lang="ts">
const { register } = useStrapiAuth()
const router = useRouter()
const onSubmit = async () => {
try {
await register({ username: '', email: '', password: '', phoneNumber: '' })
router.push('/authenticated-page')
} catch (e) {}
}
</script>
Check out the Strapi Registration documentation.
forgotPassword
This action sends an email to a user with the link to your own reset password page. The link will be enriched with the url param code that is needed for the resetPassword
.
- Arguments:
- data:
StrapiForgotPasswordData
- data:
- Returns:
Promise<void>
<script setup lang="ts">
const { forgotPassword } = useStrapiAuth()
const router = useRouter()
const onSubmit = async () => {
try {
await forgotPassword({ email: '' })
router.push('/')
} catch (e) {}
}
</script>
Check out the Strapi Forgot & Reset flow documentation.
resetPassword
This action will update the user password. Sets user
and token
.
- Arguments:
- data:
StrapiResetPasswordData
- data:
- Returns:
Promise<StrapiAuthenticationResponse>
<script setup lang="ts">
const { resetPassword } = useStrapiAuth()
const router = useRouter()
const onSubmit = async () => {
try {
await resetPassword({ code: '', password: '', passwordConfirmation: '' })
router.push('/authenticated-page')
} catch (e) {}
}
</script>
Check out the Strapi Forgot & Reset flow documentation.
changePassword
You can also update an authenticated user password through the /change-password
API endpoint:
- Arguments:
- data:
StrapiChangePasswordData
- data:
- Returns:
Promise<void>
<script setup lang="ts">
const { changePassword } = useStrapiAuth()
const onSubmit = async () => {
try {
await changePassword({ currentPassword: '', password: '', passwordConfirmation: '' })
$toast.success('Password changed!')
} catch (e) {}
}
</script>
Check out the Strapi Change password flow documentation.
sendEmailConfirmation
This action will re-send the confirmation sent after registration
.
- Arguments:
- Returns:
Promise<void>
<script setup lang="ts">
const { sendEmailConfirmation } = useStrapiAuth()
const onSubmit = async () => {
try {
await sendEmailConfirmation({ email: '' })
alert('Success!')
} catch (e) {}
}
</script>
Check out the Strapi Email validation documentation.
getProviderAuthenticationUrl
Return the correct URL to authenticate with provider.
- Arguments:
- provider:
StrapiAuthProvider
- provider:
- Returns:
string
<script setup lang="ts">
const { getProviderAuthenticationUrl } = useStrapiAuth()
const onClick = () => {
window.location.href = getProviderAuthenticationUrl('github')
}
</script>
authenticateProvider
Authenticate user with external provider. Sets user
and token
.
- Arguments:
- provider:
StrapiAuthProvider
- access_token:
string
- provider:
- Returns:
Promise<StrapiAuthenticationResponse>
<script setup lang="ts">
const { authenticateProvider } = useStrapiAuth()
const route = useRoute()
await authenticateProvider('github', route.query.access_token)
</script>
fetchUser
Fetch me
user from /users/me
route if a token
exists in the cookies then sets user
.
<script setup lang="ts">
const { fetchUser } = useStrapiAuth()
const user = await fetchUser()
</script>
Learn how to populate relations in
/users/me
route.