auth icon indicating copy to clipboard operation
auth copied to clipboard

How to refresh token with Laravel JWT

Open zerostechnology opened this issue 9 months ago • 0 comments

I'm getting "Missing refresh token" issue when using Laravel JWT. As i know, Laravel JWT doesn't provide a refresh token, but how to make it works so this plugin will call refresh token endpoint when the token is expired (BE returns 401)) and set the new token.

Here is my nuxt.config.ts

auth: {
	fullPathRedirect: true,
	globalMiddleware: true,
	stores: {
		pinia: {
			enabled: true,
		}
	},
	strategies: {
		'laravelJWT': {
			provider: 'laravel/jwt',
			url: process.env.APP_API_URL || 'http://localhost:8000',
			endpoints: {
				login: {
					url: '/api/auth/login',
				},
				refresh: {
					url: '/api/auth/refresh',
				},
				logout: {
					url: '/api/auth/logout',
				},
				user: {
					url: '/api/auth/user',
				}
			},
			token: {
				property: 'access_token',
				maxAge: 60 * 60
			},
			refreshToken: {
				maxAge: 20160 * 60
			},
			user: {
				property: false,
				autoFetch: true,
			},
		},
	}
},

I set this in useFetch()

return useFetch(request, {
    ...defaults,
    onRequest({ request, options }) {
        // Set the request headers
    },
    onRequestError({ request, options, error }) {
        // Handle the request errors
    },
    onResponse: async ({ request, response, options }) => {
        if (response.status === 401) {
            try {
              const response = await auth.refreshTokens();
              jwtToken.value = body.access_token;
    
              options.headers = { Authorization: `Bearer ${newToken}` };
              return useFetch(request, defaults);
            } catch (error) {
              console.error("Token refresh failed:", error);
            }
        }
    },
    onResponseError({ request, response, options }) {
        // Handle the response errors
    }
})

zerostechnology avatar May 06 '25 07:05 zerostechnology