Serve static JS-App from directory in Laravel for authorized users

836 Views Asked by At

I have a Js app. It has its own directory and everything it needs is in that directory. I want to use this app in Laravel project now. But it should only be available for logged in users. Now I do not know how to do it. I would use cookie-authentication, but how should it work? If JS app is in public directory it is always open for access and has no access to csrf token. If it is in resourses I can only provide single files in view. How can I make a whole directory available? At the moment I see only one possibility:

web.php

Route::middleware(['auth:sanctum', 'verified'])->get('/jsapp', function () {
    return view("jsapp");
})->name('jsapp');

Route::middleware(['auth:sanctum', 'verified'])->get('/jsapp/{path?}', function (Request $req, $path) {
    return serve_file_somehow("path_to_project_root", $path);
});

This Js-App polls the server regularly to check if the user is still logged in.My question how to implement this serve_file_somehow feature? Or maybe there are other solutions for this situation? Is there any kind of .htaccess -magic that can be implemented?

Js-App directory structure:

resources/views/jsapp
-- index.html
    <html>
        <link href="css/styles.css" />
        <script src="js/index.js />
    </html>
-- css/styles.css
-- js/index.js
-- images/img1.jpg

What bothers me is that you reimplement the functions of a web server via PHP/Laravel.

2

There are 2 best solutions below

3
On BEST ANSWER

You should serve the index.html file contents through a blade template index.blade.php

<html>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <link href="/css/styles.css" />
  <script src="/js/index.js />
</html>

with a protected route:

Route::middleware(['auth:sanctum', 'verified'])->get('/jsapp', function () {
    return view("jsapp.index");
})->name('jsapp');

and put all javascript and css files in the public directory.

0
On

It is also possible to get CSRF token via XSRF-TOKEN cookie, which Laravel sets automatically. If you don't have access to the resources directory, or want to have all your JS app in one directory. Then you can also use this method.

 <script>
    $.ajaxSetup({
        headers: {
            'X-XSRF-TOKEN': $.cookie('XSRF-TOKEN')
        }
    });
 </script>