EinLinuus's avatar

Inertia: API Requests

Hey, I'm a bit confused on how to make API requests in Inertia. I have a React component and want to do a non-inertia-request to the Laravel backend.

Example: I have a component where the user can select a company or create a new one. This opens a modal, user fills out the fields, new company is created, select field automatically selects the newly created company. I can't use regular Inertia requests here, because that would reload the page. Also, there are times where I explicitly don't want the inertia request behavior and just need a regular API/fetch request.

Are these routes API routes (do I need Sanctum?), or just regular web routes, but how do I handle CSRF tokens? I've seen "use axios, it's already configured" many times, but it looks like axios is not included in the official Laravel starter kits and not pre-configured.

Thanks for any help :)

Here is a code example, maybe this helps to understand what I want to achieve:

<?php

class CompanyController extends Controller {
		public function store(Request $request)
		{
				$validated = $request->validate([
						'name' => 'required|string|min:3',
						// ...
				]);

				$company = Company::create($validated);

				return response()->json([
						'company' => $company,
				]);
		}
}
interface Props {
		onCompanyCreate?: (company: Company) => unknown;
}

export default function CompanySelectAndCreate(props: Props) {
		const [data, setData] = useState({
				name: '',
		});

		const save = () => {
				const result = // TODO: how to request CompanyController::store()
				
				if(props.onCompanyCreate) {
						props.onCompanyCreate(result.company); 
				}
		};

		return <form onSubmit={event => {
				event.preventDefault();
				save();
		}}>
				{/* ... */}
		</form>
}
0 likes
3 replies
LaryAI's avatar
Level 58

Certainly! Here’s a clear solution to your question about making non-Inertia API requests from a React component in an Inertia.js/Laravel app.


1. Use Axios or Fetch for API Requests

You can use either axios or the native fetch API to make requests to your Laravel backend. Axios is commonly used because of its simplicity and automatic CSRF token handling (with some setup).

2. API vs Web Routes

  • If your React component is making requests that don’t require a full page reload or Inertia navigation, you can use either API routes (routes/api.php) or web routes (routes/web.php).
  • If you use API routes, authentication is usually handled via Laravel Sanctum or Passport.
  • If you use web routes, you need to handle CSRF tokens for POST/PUT/DELETE requests.

3. CSRF Token Handling

  • For web routes, you need to include the CSRF token in your requests.
  • Laravel includes the CSRF token as a meta tag in your HTML by default:
<meta name="csrf-token" content="{{ csrf_token() }}">
  • You can grab this token in your JavaScript and include it in your requests.

4. Example: Using Axios

First, install axios if you haven’t:

npm install axios

Then, set up axios to include the CSRF token by default:

import axios from 'axios';

// Get CSRF token from meta tag
const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

axios.defaults.headers.common['X-CSRF-TOKEN'] = token;
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Now, you can make a POST request to create a company:

axios.post('/companies', {
    name: 'New Company',
    // ...other fields
})
.then(response => {
    // Handle success, e.g., update your select field
})
.catch(error => {
    // Handle error
});

5. Example: Using Fetch

If you prefer fetch:

const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

fetch('/companies', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': token,
        'X-Requested-With': 'XMLHttpRequest',
    },
    body: JSON.stringify({
        name: 'New Company',
        // ...other fields
    }),
})
.then(response => response.json())
.then(data => {
    // Handle success
})
.catch(error => {
    // Handle error
});

6. Do You Need Sanctum?

  • If you use API routes (routes/api.php), you generally need Sanctum for authentication.
  • If you use web routes, and your user is already authenticated via Laravel session, you don’t need Sanctum—just make sure to include the CSRF token.

Summary

  • Use axios or fetch for non-Inertia requests.
  • For web routes, include the CSRF token.
  • For API routes, use Sanctum for authentication.
  • Axios is not pre-installed, but you can easily install and configure it as shown above.

Let me know if you need a more specific example or further clarification!

JussiMannisto's avatar
Level 50

but it looks like axios is not included in the official Laravel starter kits and not pre-configured.

Axios is used by Inertia, so it should be included. You can check that by running npm list axios.

If the new starter kits don't configure an Axios client automatically, you can do it yourself. Create a bootstrap.js file in resources/js, something like this:

import axios from 'axios';
window.axios = axios;

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.withCredentials = true;
window.axios.defaults.withXSRFToken = true;

Then import it in the app.jsx/.tsx file:

import './bootstrap';

When you load a page, Laravel includes an XSRF-TOKEN cookie in the response. Axios automatically reads it and includes it in all future requests as a header.

If you're sending requests from the browser, you can place those routes in the web routes. That's the simplest as it allows you to use cookies for authentication without extra configuration.

Ps. If you're only sending same-origin requests, you don't need the withCredentials and withXSRFToken options.

1 like

Please or to participate in this conversation.