InertiaJS is a really impressive approach to building fullstack web applications. I've probably first heard about it in the Javascript Jabber from devchat.tv in episode 443. Adopting it was really straightforward as I had previous experiences with Laravel, TailwindCSS and Svelte (which is still my choice for front-end).
The problem
The only problem I keep seeing is this error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/item?page=2. (Reason: CORS request did not succeed)
CORS or Cross-Origin Resource Sharing is a security feature, and it is
nothing new. The reason the message is showing in my situation is because
of the
Browsersync reloading in Laravel Mix.
The way Browsersync works is that it is proxying the host URL, in my case
http://localhost
into another one that is fully under control of the
Browsersync, the default one being http://localhost:3000/
. I am not
entirely sure what happens under the Browsersync's hood at this point, so
feel free to let me know if there is a better way to explain it. Surely
there is.
A solution
Anyway, there seem to be an accepted solution how to deal with this problem. I've included most relevant-ish links down below, but in general, two steps are required:
Step 1. Configure Browsersync options
If using Browsersync via Laravel Mix, insert the following in the
webpack.mix.js
:
.browserSync({
proxy: 'localhost',
host: 'localhost:3000'
})
Step 2. Inform the front-end
Insert the following line in to resources/views/app.blade.php
, almost at
the very bottom of the page:
@if (app()->isLocal())
<script src="http://localhost:3000/browser-sync/browser-sync-client.js"></script>
@endif
<!-- here is the end of the page
</body>
</html>
-->
Step 3. Watch
Now start watching the app in the browser tab at http://localhost:3000
that gets opened and then reloaded automatically when resources change:
npm run watch
I have two problems with this solution. The first is that the script part gets propagated into the production bundle, but is pointing at the non-existent file. Not that much of a problem and can be solved, although the solution should be readily offered.
The second, worse one is that on the things like pagination, the URL does get proxied only after the full page refresh. After navigating in an InertiaJS app, the proxy stops working, which is quite distracting during the development. I will try to open the issue when I learn more about the actual behavior.
Links
- https://warrickbayman.medium.com/browsersync-and-inertia-8e3ed647669a
- https://angle.software/configuring-mix-livereload-browsersync-with-inertiajs/
- https://forum.laravel-livewire.com/t/getting-cors-error-on-file-upload-probably-related-to-browsersync/1565/2
- https://laracasts.com/discuss/channels/code-review/laravel-redirect-failing-cors?page=1&replyId=634427
- https://github.com/inertiajs/inertia-laravel/issues/57#issuecomment-570581851