Handling expired token in Laravel

Handling expired token in Laravel

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Expired Tokens in Laravel Without Page Refreshes

When an Ajax request returns a TOKEN MISMATCH error after a period of inactivity, it usually means the CSRF token stored on the client side has become invalid relative to the server's expectation. In Laravel, this often happens because the session or the cookie containing the token has expired, or the token itself has been rotated by a new request that invalidated the old one. The immediate reaction is to refresh the page, but that forces a full reload of assets and re-initializes the application state. A more robust solution involves intercepting the failure at the network level or refreshing the token programmatically before it blocks your critical API calls.

The most straightforward approach without reloading the page is to automatically regenerate the CSRF token upon detecting an error or after a specific timeout window. Laravel provides a helper method specifically for this: csrf_token(). You can create a JavaScript utility that runs on page load, fetches the fresh token from the meta tag, and updates the global variable used by your Ajax requests.

// Fetch the fresh token immediately upon page load
const updateToken = () => {
    const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
    
    if (token) {
        // Update the global variable or store in localStorage
        window.csrfToken = token; 
        // If you use a specific name like 'X-CSRF-TOKEN' header, ensure your Axios/Ajax setup uses this
    }
};

document.addEventListener('DOMContentLoaded', updateToken);

By updating the token at page load, you ensure that any subsequent Ajax requests use the current valid key. However, this only solves the problem if the token expires strictly due to session timeout. If the server has actively invalidated the token (e.g., via a force_reset in Laravel sessions or strict CSRF rotation policies), simply reading the meta tag might not be enough if the meta tag itself hasn't updated yet.

In scenarios where you cannot rely on page load timing or need to handle mid-session expirations, implementing an interceptor is the superior architectural choice. Using Axios or a similar library, you can catch errors at the request level. When a TOKEN MISMATCH response is detected (typically status code 419 in Laravel), you can trigger a silent refresh of the token and retry the failed request with the new value.

axios.interceptors.response.use(
    response => response,
    error => {
        if (error.response && error.response.status === 419) {
            // Token mismatch detected
            const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
            
            if (token) {
                // Re-queue the failed request with the new token
                // Or redirect to a refresh endpoint if the token is truly stale
                window.location.reload(); 
            } else {
                console.error("CSRF token could not be refreshed");
            }
        }
        return Promise.reject(error);
    }
);

This pattern ensures that your application remains responsive even when session states diverge. The trade-off here is adding complexity to your error handling logic. You must decide whether to retry immediately or redirect the user. Retrying immediately feels seamless but might loop if the server hasn't fully updated its state. Redirecting forces a page load, which defeats the purpose of avoiding refreshes unless that redirect is to a specific "token refresh" route.

Another consideration is how you store the token. Storing it in localStorage is generally safer than relying on cookies for Ajax requests if your session configuration uses sameSite: 'lax' or stricter settings, although Laravel defaults usually handle this well out of the box. Ensure that your meta tag remains consistent with the session cookie's lifetime. If you are using Laravel 9 or later, be mindful of changes to default session configurations which might alter how tokens are validated by default.

For production applications where maintaining a seamless user experience is critical, consider implementing a dedicated "refresh" endpoint. This route regenerates the token and updates the meta tag without requiring a full page reload. Your interceptor can then call this endpoint whenever it detects a mismatch.

// Example route in Laravel to refresh the token
Route::get('/refresh-token', function () {
    $token = csrf_token();
    return response()->view('tokens.refresh', ['token' => $token]);
});

By combining automatic updates on load with an interceptor strategy for mid-session expirations, you eliminate the need for manual page refreshes while maintaining security integrity. This approach respects Laravel's CSRF mechanisms without compromising the user experience of your Ajax-driven interface.

Our network