Nuxt Auth - Remember Me

10th October 2020

Nuxt makes it very easy to add authentication with its auth and auth-next (still in-development, and the one used through this article) plugin. There is even, within the auth-next plugin, support for the relatively new Laravel Sanctum. But what if you want to add remember me functionality to your application? Neither of the above mentioned plugins currently offer support for this addition, so how easy is it to add?

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.

auth: {
	cookie: {
		options: {
			maxAge: 86400 // 24 hours

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.

login () {
	return this.$auth.loginWith(
		{ data: this.form }
	).then(() => {
		// if we are remembering the user, we
		// need to set the remember cookie
		if (this.form.remember_me) {
				{ maxAge: 2147483647 }

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

auth: {
  plugins: ['~/plugins/auth.js'],

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

export default function ({ $auth }) {
	const remember = $auth.$storage.getCookie(`_remember.${$auth.options.defaultStrategy}`)

	if (typeof remember !== 'undefined') {
		if ($auth.strategy.token.get() !== remember) {