Nuxt Auth - Remember Me

October 10th, 2020

Within your nuxt.config.js file you can add settings for the auth plugin, including options for the cookies. One of these is the cookies max age. In theory, this cookie would need two settings: one for when the user isn't being remembered and one for when they are. However, this isn't possible. Instead simply set it to the max age for when the user isn't being remembered, I usually go for 24 hours.

1auth: {
2 cookie: {
3 options: {
4 maxAge: 86400 // 24 hours
5 }
6 },
7 ...
8},

Now when a user logs into your application, all of the cookies that the auth plugin sets will have a max age of 24 hours. But if they have selected the option to "remember_me" we would require this to be longer.

In order to work around this, we need to do two things. First, set a remember me cookie that has a long max age, so we know that the user is being remembered for future use, and contains the created token. Secondly, use this remember token to set the auth user token if required.

In the login method we will check if remember me has been checked, if so we will set a cookie prefixed "remember" and attached to the default strategy with a long max age. The value of this cookie, must be set to the new user token.

1login () {
2 return this.$auth.loginWith(
3 this.$auth.options.defaultStrategy,
4 { data: this.form }
5 ).then(() => {
6 // if we are remembering the user, we
7 // need to set the remember cookie
8 if (this.form.remember_me{
9 this.$auth.$storage.setCookie(
10 `_remember.${this.$auth.options.defaultStrategy}`,
11 this.$auth.strategy.token.get(),
12 { maxAge: 2147483647 }
13 )
14 }
15 })
16},

Next, we'll add an auth plugin to the nuxt.config.js file...

1auth: {
2 plugins: ['~/plugins/auth.js'],
3}

...and in the plugin we will check for the existence of the remember cookie and set the user token if required.

1export default function ({ $auth }) {
2 const remember = $auth.$storage.getCookie(`_remember.${$auth.options.defaultStrategy}`)
3 
4 if (typeof remember !== 'undefined'{
5 if ($auth.strategy.token.get() !== remember{
6 $auth.setUserToken(remember)
7 }
8 }
9}