Laravel With inertiajs-react get 419 Error (Page expired) when trying to login.
When trying to login to a Laravel application using InertiaJS-React, you might encounter a 419 Error (Page expired) issue. This error typically occurs when the server expects a fresh CSRF token, but the token provided in the request is stale or invalid.
To resolve this issue, follow the steps below:
- Ensure CSRF Protection is enabled in Laravel
CSRF protection is a security feature in Laravel that helps prevent unauthorized requests. Make sure that CSRF protection is enabled in your Laravel application by adding the following line to the kernel.php
file in the app/Http
directory:
protected $middlewareGroups = [
'web' => [
// ...
\Illuminate\Cookie\Middleware\CSRFCookie::class,
\Illuminate\Cookie\Middleware\CSRFToken::class,
// ...
],
];
- Update InertiaJS-React to the latest version
Make sure you are using the latest version of InertiaJS-React to avoid any known issues. You can check the latest version on the official GitHub repository: https://github.com/inertiajs/inertia-react
- Configure InertiaJS-React with CSRF Protection
To configure InertiaJS-React with CSRF protection, you need to install the @inertiajs/react-csrf
package and import it in your app.js
file.
First, install the package using npm or yarn:
npm install @inertiajs/react-csrf
# or
yarn add @inertiajs/react-csrf
Next, import the package in your app.js
file:
import CSRF from '@inertiajs/react-csrf';
function App() {
return (
<CSRF.Provider value={csrfToken => window.csrfToken = csrfToken}>
{/* Your application code */}
</CSRF.Provider>
);
}
export default App;
- Update your login form
Update your login form to include the CSRF token in the request. You can do this by wrapping your form component with the CSRF.Form
component from InertiaJS-React:
import CSRF from '@inertiajs/react-csrf';
function LoginForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = useCallback(
(e) => {
e.preventDefault();
axios.post('/login', {
email,
password,
_token: window.csrfToken,
});
},
[email, password, window.csrfToken]
);
return (
<CSRF.Form onSubmit={handleSubmit}>
<form onSubmit={handleSubmit}>
{/* Your form fields */}
<button type="submit">Login</button>
</form>
</CSRF.Form>
);
}
By following the steps above, you should be able to resolve the 419 Error (Page expired) issue when trying to login to your Laravel application using InertiaJS-React.