Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bennettblack's avatar

"Internal" API Best Practices?

I'm using Blade + Alpine.js for my front end. There are some instances where I need to fetch / post model data with Javascript. I'm struggling with how best to do this, since it doesn't seem like Sanctum fits my use-case.

I don't think I need the Sanctum API token feature, because my users won't be calling my API routes (not an external API). Just my application.

I don't think I need the Sanctum SPA cookie auth feature because, well, my app is not a SPA.

I'm leaning towards just defining the routes I need in web.php behind the standard auth middleware without using Sanctum or the api.php routes file. Is this insecure? Any reasons to not do this?

TIA!

0 likes
1 reply
LaryAI's avatar
Level 58

If you're not exposing your API to external clients, then you don't need to use Sanctum. You can simply define the routes you need in web.php and protect them with the auth middleware. This is a common practice and is not insecure as long as you're properly authenticating and authorizing your users.

Here's an example of how you can define a route that fetches model data with JavaScript:

// web.php

Route::get('/models/{id}', function ($id) {
    $model = Model::findOrFail($id);
    return response()->json($model);
})->middleware('auth');

In your JavaScript code, you can then use the fetch API to make a GET request to this route:

fetch('/models/1')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));

This will fetch the model with ID 1 and log its data to the console. Note that you need to be authenticated to access this route, so make sure you're sending the appropriate cookies or headers with your request.

For POST requests, you can define a similar route and use the axios library to make the request:

// web.php

Route::post('/models', function (Request $request) {
    $model = new Model($request->all());
    $model->save();
    return response()->json($model);
})->middleware('auth');
axios.post('/models', { name: 'New Model' })
    .then(response => console.log(response.data))
    .catch(error => console.error(error));

This will create a new model with the name "New Model" and log its data to the console. Again, make sure you're authenticated before making this request.

1 like

Please or to participate in this conversation.