jan_zikmund's avatar

SPA route group and auth

Hi, I am about to build a Vue SPA only using my own endpoints with Laravel back-end, and there is a few concepts I just want to clarify:

  1. Which route group shall I use? I assume routes/api.php as the front-end will communicate through API endpoints, and then I probably need Sanctum to handle authentication, correct?

  2. But what is the befit of the above compared to using web routes group? In my previous apps I used standard Laravel login form which gave user the session, then I put my routes to web group and applied auth middleware and it seemed to work fine too. So in my case (only my app using the api endpoints), only difference I see is that with Sanctum/api_routes I can use even the login form buit in Spa. While using web routes the form has to post the standard way, and then my Spa loads after user authenticates the standard way. Does it make sense or am I missing something?

Thanks a lot

0 likes
4 replies
fylzero's avatar

@jan_zikmund Actually in apps that I am just using standard Laravel auth on and want to separate the routes I use for Vue internally... I'll just create a new group.

Create this file...

routes/vue.php

<?php

use Illuminate\Support\Facades\Route;

Route::get('thing', 'ThingController@index');

Then edit this file and add the appropriate code...

app/Providers/RouteServiceProvider.php


    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        $this->mapVueRoutes();

        //
    }



    /**
     * Define the "vue" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapVueRoutes()
    {
        Route::prefix('vue')
            ->middleware(['web', 'auth'])
            ->namespace($this->namespace)
            ->group(base_path('routes/vue.php'));
    }

Now everything you put in the vue.php route file can be pulled from Axios using axios.get('/vue/thing')

24 likes
fylzero's avatar

Alternately, if you are using Sanctum and fully replacing Laravel auth... just use the api.php. It makes sense that you are building an API with an SPA, not using web routes for that.

24 likes
jan_zikmund's avatar

Just getting back to my own thread in case anyone was interested - indeed looks like Sanctum is exactly what I needed. routes/web.php will only contain auth routs and main fallback route to generate SPA homepage. Then routes/api.php will contain all api routes used within the SPA and being guarded by auth:sanctum middleware.

There is a nice tutorial that took me through it here

Please or to participate in this conversation.