[{"data":1,"prerenderedAt":2182},["ShallowReactive",2],{"series-\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbridging-the-gap-connecting-your-frontend-and-backend":3,"series-context-\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api":1970},{"id":4,"title":5,"body":6,"contentId":1957,"date":1958,"description":1959,"extension":1960,"github":1961,"meetTheInstructor":1961,"meta":1962,"navigation":131,"part":152,"path":1963,"rawbody":1964,"robots":1961,"schemaOrg":1961,"seo":1965,"seriesSlug":1966,"sitemap":1967,"stem":1968,"subtitle":1961,"topics":1961,"__hash__":1969},"series\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbridging-the-gap-connecting-your-frontend-and-backend.md","Bridging the Gap: Connecting Your Frontend and Backend",{"type":7,"value":8,"toc":1949},"minimark",[9,13,30,33,41,46,55,58,85,88,105,108,111,114,258,261,268,271,321,324,334,337,369,372,379,399,402,405,420,470,473,524,529,538,599,602,607,642,645,660,671,678,682,685,692,697,704,711,721,729,732,950,965,968,977,1066,1071,1090,1095,1107,1149,1157,1166,1169,1173,1176,1187,1203,1210,1213,1347,1354,1384,1387,1390,1393,1400,1405,1408,1795,1802,1805,1812,1815,1818,1824,1851,1862,1869,1926,1929,1933,1936,1945],[10,11,12],"p",{},"With post synchronization in place, the next step is to connect the VitePress site to the Laravel API.",[10,14,15,16,23,24,29],{},"Because the two applications will be deployed separately, this involves more than sending a request to a URL. We need to configure ",[17,18,22],"a",{"href":19,"rel":20},"https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FCross-origin_resource_sharing",[21],"nofollow","CORS (Cross-Origin Resource Sharing)"," and ",[17,25,28],{"href":26,"rel":27},"https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FCross-site_request_forgery",[21],"CSRF (Cross-Site Request Forgery)"," protection, then ensure that the browser sends the credentials Laravel needs for session-based authentication.",[10,31,32],{},"The configuration can feel intimidating at first, but we will handle it one piece at a time. Laravel provides most of the pieces we need.",[34,35,38],"callout",{"color":36,"icon":37},"success","i-ph-lightbulb-duotone",[10,39,40],{},"I recommend reading the linked articles if you want a deeper explanation of these concepts. It will make the configuration in this article easier to understand.",[42,43,45],"h2",{"id":44},"installing-laravel-sanctum","Installing Laravel Sanctum",[10,47,48,49,54],{},"The Laravel ecosystem provides ",[17,50,53],{"href":51,"rel":52},"https:\u002F\u002Flaravel.com\u002Fdocs\u002F12.x\u002Fsanctum#spa-authentication",[21],"Sanctum",", which supports both API tokens and cookie-based authentication for Single Page Applications (SPAs).",[10,56,57],{},"To get started, let's install Sanctum:",[59,60,66],"pre",{"className":61,"code":62,"filename":63,"language":64,"meta":65,"style":65},"language-bash shiki shiki-themes github-light github-light github-dark","php artisan install:api\n","terminal","bash","",[67,68,69],"code",{"__ignoreMap":65},[70,71,74,78,82],"span",{"class":72,"line":73},"line",1,[70,75,77],{"class":76},"snPdu","php",[70,79,81],{"class":80},"sIIMD"," artisan",[70,83,84],{"class":80}," install:api\n",[10,86,87],{},"Then, let's publish the cors configuration file:",[59,89,91],{"className":61,"code":90,"filename":63,"language":64,"meta":65,"style":65},"php artisan config:publish cors\n",[67,92,93],{"__ignoreMap":65},[70,94,95,97,99,102],{"class":72,"line":73},[70,96,77],{"class":76},[70,98,81],{"class":80},[70,100,101],{"class":80}," config:publish",[70,103,104],{"class":80}," cors\n",[10,106,107],{},"CORS, or Cross-Origin Resource Sharing, is a browser security mechanism. By default, browsers prevent a page from making requests to a different origin. This protects users from malicious sites making unauthorized requests on their behalf.",[10,109,110],{},"Our frontend needs to communicate with an API hosted on another origin, so we must explicitly allow that origin in the API configuration.",[10,112,113],{},"Speaking of which, let's configure CORS to allow requests from our frontend:",[59,115,119],{"className":116,"code":117,"filename":118,"language":77,"meta":65,"style":65},"language-php shiki shiki-themes github-light github-light github-dark has-highlighted","\u003C?php\n\ndeclare(strict_types=1);\n\nreturn [\n    'paths' => ['api\u002F*', 'sanctum\u002Fcsrf-cookie'],\n\n    'allowed_methods' => ['*'],\n\n    'allowed_origins' => [\n        env('APP_FRONTEND_URL'), \u002F\u002F [!code ++]\n    ],\n\n    'allowed_origins_patterns' => [],\n\n    'allowed_headers' => ['*'],\n\n    'exposed_headers' => [],\n\n    'max_age' => 0,\n\n    'supports_credentials' => true, \u002F\u002F [!code highlight]\n\n];\n","config\u002Fcors.php",[67,120,121,126,133,139,144,150,156,161,167,172,178,184,190,195,201,206,212,217,223,228,234,239,247,252],{"__ignoreMap":65},[70,122,123],{"class":72,"line":73},[70,124,125],{},"\u003C?php\n",[70,127,129],{"class":72,"line":128},2,[70,130,132],{"emptyLinePlaceholder":131},true,"\n",[70,134,136],{"class":72,"line":135},3,[70,137,138],{},"declare(strict_types=1);\n",[70,140,142],{"class":72,"line":141},4,[70,143,132],{"emptyLinePlaceholder":131},[70,145,147],{"class":72,"line":146},5,[70,148,149],{},"return [\n",[70,151,153],{"class":72,"line":152},6,[70,154,155],{},"    'paths' => ['api\u002F*', 'sanctum\u002Fcsrf-cookie'],\n",[70,157,159],{"class":72,"line":158},7,[70,160,132],{"emptyLinePlaceholder":131},[70,162,164],{"class":72,"line":163},8,[70,165,166],{},"    'allowed_methods' => ['*'],\n",[70,168,170],{"class":72,"line":169},9,[70,171,132],{"emptyLinePlaceholder":131},[70,173,175],{"class":72,"line":174},10,[70,176,177],{},"    'allowed_origins' => [\n",[70,179,181],{"class":72,"line":180},11,[70,182,183],{},"        env('APP_FRONTEND_URL'), \u002F\u002F [!code ++]\n",[70,185,187],{"class":72,"line":186},12,[70,188,189],{},"    ],\n",[70,191,193],{"class":72,"line":192},13,[70,194,132],{"emptyLinePlaceholder":131},[70,196,198],{"class":72,"line":197},14,[70,199,200],{},"    'allowed_origins_patterns' => [],\n",[70,202,204],{"class":72,"line":203},15,[70,205,132],{"emptyLinePlaceholder":131},[70,207,209],{"class":72,"line":208},16,[70,210,211],{},"    'allowed_headers' => ['*'],\n",[70,213,215],{"class":72,"line":214},17,[70,216,132],{"emptyLinePlaceholder":131},[70,218,220],{"class":72,"line":219},18,[70,221,222],{},"    'exposed_headers' => [],\n",[70,224,226],{"class":72,"line":225},19,[70,227,132],{"emptyLinePlaceholder":131},[70,229,231],{"class":72,"line":230},20,[70,232,233],{},"    'max_age' => 0,\n",[70,235,237],{"class":72,"line":236},21,[70,238,132],{"emptyLinePlaceholder":131},[70,240,244],{"class":241,"line":243},[72,242],"highlighted",22,[70,245,246],{},"    'supports_credentials' => true,",[70,248,250],{"class":72,"line":249},23,[70,251,132],{"emptyLinePlaceholder":131},[70,253,255],{"class":72,"line":254},24,[70,256,257],{},"];\n",[10,259,260],{},"We will discuss deployment later, but remember that we are creating two applications: the blog and the API that enriches it. They will be deployed separately, which is why the API must allow requests from the blog.",[34,262,265],{"color":263,"icon":264},"info","i-ph-info-duotone",[10,266,267],{},"We could deploy both applications behind the same domain with a reverse proxy, but that would add complexity that we do not need here.",[10,269,270],{},"Then, we need to configure Sanctum to allow requests from our frontend:",[59,272,275],{"className":116,"code":273,"filename":274,"language":77,"meta":65,"style":65},"return [\n    'stateful' => explode(',', (string) env('SANCTUM_STATEFUL_DOMAINS', sprintf(\n        '%s%s',\n        'localhost:4173,localhost:5173', \u002F\u002F [!code highlight]\n        Sanctum::currentApplicationUrlWithPort()\n    ))),\n\n  \u002F\u002F ...\n]\n","config\u002Fsanctum.php",[67,276,277,281,286,291,297,302,307,311,316],{"__ignoreMap":65},[70,278,279],{"class":72,"line":73},[70,280,149],{},[70,282,283],{"class":72,"line":128},[70,284,285],{},"    'stateful' => explode(',', (string) env('SANCTUM_STATEFUL_DOMAINS', sprintf(\n",[70,287,288],{"class":72,"line":135},[70,289,290],{},"        '%s%s',\n",[70,292,294],{"class":293,"line":141},[72,242],[70,295,296],{},"        'localhost:4173,localhost:5173',",[70,298,299],{"class":72,"line":146},[70,300,301],{},"        Sanctum::currentApplicationUrlWithPort()\n",[70,303,304],{"class":72,"line":152},[70,305,306],{},"    ))),\n",[70,308,309],{"class":72,"line":158},[70,310,132],{"emptyLinePlaceholder":131},[70,312,313],{"class":72,"line":163},[70,314,315],{},"  \u002F\u002F ...\n",[70,317,318],{"class":72,"line":169},[70,319,320],{},"]\n",[10,322,323],{},"The important change is adding the frontend's development origins to Sanctum's stateful domains.",[10,325,326,327,23,330,333],{},"A browser origin combines the protocol, hostname, and port. During development, ",[67,328,329],{},"localhost:5173",[67,331,332],{},"localhost:8000"," are different origins even though they share the same hostname.",[10,335,336],{},"Then, we need to add a middleware:",[59,338,342],{"className":339,"code":340,"filename":341,"language":77,"meta":65,"style":65},"language-php shiki shiki-themes github-light github-light github-dark","return Application::configure(basePath: dirname(__DIR__))\n    ->withMiddleware(function (Middleware $middleware): void {\n        $middleware->statefulApi(); \u002F\u002F [!code ++]\n    })\n     ->create();\n","bootstrap\u002Fapp.php",[67,343,344,349,354,359,364],{"__ignoreMap":65},[70,345,346],{"class":72,"line":73},[70,347,348],{},"return Application::configure(basePath: dirname(__DIR__))\n",[70,350,351],{"class":72,"line":128},[70,352,353],{},"    ->withMiddleware(function (Middleware $middleware): void {\n",[70,355,356],{"class":72,"line":135},[70,357,358],{},"        $middleware->statefulApi(); \u002F\u002F [!code ++]\n",[70,360,361],{"class":72,"line":141},[70,362,363],{},"    })\n",[70,365,366],{"class":72,"line":146},[70,367,368],{},"     ->create();\n",[10,370,371],{},"This middleware tells Sanctum to authenticate requests with Laravel's session cookie instead of an API token. That is the approach we will use from the frontend.",[10,373,374,375,378],{},"Finally, we need to change our authentication middleware in the ",[67,376,377],{},"routes\u002Fapi.php"," file. Actually, we use the default Laravel middleware which ensure that requests respect the Sanctum configuration like the stateful domains.",[59,380,382],{"className":339,"code":381,"filename":377,"language":77,"meta":65,"style":65},"Route::middleware('auth:sanctum')->group(function () { \u002F\u002F [!code highlight]\n    \u002F\u002F Handle authenticated requests...\n});\n",[67,383,384,389,394],{"__ignoreMap":65},[70,385,386],{"class":72,"line":73},[70,387,388],{},"Route::middleware('auth:sanctum')->group(function () { \u002F\u002F [!code highlight]\n",[70,390,391],{"class":72,"line":128},[70,392,393],{},"    \u002F\u002F Handle authenticated requests...\n",[70,395,396],{"class":72,"line":135},[70,397,398],{},"});\n",[10,400,401],{},"Our backend is now ready to accept requests from the frontend.",[10,403,404],{},"Before moving to the frontend, finish a few backend changes.",[406,407,408],"ol",{},[409,410,411,412,415,416,419],"li",{},"Update ",[67,413,414],{},"store"," in ",[67,417,418],{},"RegisteredViaGitHubController"," so it redirects the user to the frontend:",[59,421,424],{"className":339,"code":422,"filename":423,"language":77,"meta":65,"style":65},"final class RegisteredViaGitHubController extends Controller\n{\n    public function store(): RedirectResponse\n    {\n        \u002F\u002F ...\n\n        return redirect(Config::get('app.frontend_url'));\n    }\n}\n","app\u002FHttp\u002FControllers\u002FRegisteredViaGitHubController.php",[67,425,426,431,436,441,446,451,455,460,465],{"__ignoreMap":65},[70,427,428],{"class":72,"line":73},[70,429,430],{},"final class RegisteredViaGitHubController extends Controller\n",[70,432,433],{"class":72,"line":128},[70,434,435],{},"{\n",[70,437,438],{"class":72,"line":135},[70,439,440],{},"    public function store(): RedirectResponse\n",[70,442,443],{"class":72,"line":141},[70,444,445],{},"    {\n",[70,447,448],{"class":72,"line":146},[70,449,450],{},"        \u002F\u002F ...\n",[70,452,453],{"class":72,"line":152},[70,454,132],{"emptyLinePlaceholder":131},[70,456,457],{"class":72,"line":158},[70,458,459],{},"        return redirect(Config::get('app.frontend_url'));\n",[70,461,462],{"class":72,"line":163},[70,463,464],{},"    }\n",[70,466,467],{"class":72,"line":169},[70,468,469],{},"}\n",[10,471,472],{},"Update its test as well:",[59,474,477],{"className":339,"code":475,"filename":476,"language":77,"meta":65,"style":65},"\u002F\u002F ...\n\ntest('redirects to the frontend', function () {\n    fakeGitHubUser();\n\n    $this->get(route('auth.github.callback'))\n        ->assertRedirect(config('app.frontend_url')); \u002F\u002F [!code highlight]\n});\n\n\u002F\u002F ...\n","tests\u002FHttp\u002FRegisteredViaGitHub\u002FStoreTest.php",[67,478,479,484,488,493,498,502,507,512,516,520],{"__ignoreMap":65},[70,480,481],{"class":72,"line":73},[70,482,483],{},"\u002F\u002F ...\n",[70,485,486],{"class":72,"line":128},[70,487,132],{"emptyLinePlaceholder":131},[70,489,490],{"class":72,"line":135},[70,491,492],{},"test('redirects to the frontend', function () {\n",[70,494,495],{"class":72,"line":141},[70,496,497],{},"    fakeGitHubUser();\n",[70,499,500],{"class":72,"line":146},[70,501,132],{"emptyLinePlaceholder":131},[70,503,504],{"class":72,"line":152},[70,505,506],{},"    $this->get(route('auth.github.callback'))\n",[70,508,509],{"class":72,"line":158},[70,510,511],{},"        ->assertRedirect(config('app.frontend_url')); \u002F\u002F [!code highlight]\n",[70,513,514],{"class":72,"line":163},[70,515,398],{},[70,517,518],{"class":72,"line":169},[70,519,132],{"emptyLinePlaceholder":131},[70,521,522],{"class":72,"line":174},[70,523,483],{},[406,525,526],{"start":128},[409,527,528],{},"Add a database seeder that generates sample comments:",[34,530,531],{"color":36,"icon":37},[10,532,533,534,537],{},"Remove the existing contents of the seeder's ",[67,535,536],{},"run"," method before adding this code.",[59,539,542],{"className":339,"code":540,"filename":541,"language":77,"meta":65,"style":65},"use App\\Models\\Post;\n\nfinal class DatabaseSeeder extends Seeder\n{\n    public function run(): void\n    {\n        Post::factory()\n            ->count(10)\n            ->hasComments(5)\n            ->create();\n    }\n}\n","database\u002Fseeders\u002FDatabaseSeeder.php",[67,543,544,549,553,558,562,567,571,576,581,586,591,595],{"__ignoreMap":65},[70,545,546],{"class":72,"line":73},[70,547,548],{},"use App\\Models\\Post;\n",[70,550,551],{"class":72,"line":128},[70,552,132],{"emptyLinePlaceholder":131},[70,554,555],{"class":72,"line":135},[70,556,557],{},"final class DatabaseSeeder extends Seeder\n",[70,559,560],{"class":72,"line":141},[70,561,435],{},[70,563,564],{"class":72,"line":146},[70,565,566],{},"    public function run(): void\n",[70,568,569],{"class":72,"line":152},[70,570,445],{},[70,572,573],{"class":72,"line":158},[70,574,575],{},"        Post::factory()\n",[70,577,578],{"class":72,"line":163},[70,579,580],{},"            ->count(10)\n",[70,582,583],{"class":72,"line":169},[70,584,585],{},"            ->hasComments(5)\n",[70,587,588],{"class":72,"line":174},[70,589,590],{},"            ->create();\n",[70,592,593],{"class":72,"line":180},[70,594,464],{},[70,596,597],{"class":72,"line":186},[70,598,469],{},[10,600,601],{},"This creates 10 posts with five comments each, giving us data to use while testing the frontend.",[406,603,604],{"start":135},[409,605,606],{},"Recreate the database and run the migrations:",[59,608,610],{"className":61,"code":609,"filename":63,"language":64,"meta":65,"style":65},"rm database\u002Fdatabase.sqlite && touch database\u002Fdatabase.sqlite && php artisan migrate --seed\n",[67,611,612],{"__ignoreMap":65},[70,613,614,617,620,624,627,629,631,633,635,638],{"class":72,"line":73},[70,615,616],{"class":76},"rm",[70,618,619],{"class":80}," database\u002Fdatabase.sqlite",[70,621,623],{"class":622},"sxrX7"," && ",[70,625,626],{"class":76},"touch",[70,628,619],{"class":80},[70,630,623],{"class":622},[70,632,77],{"class":76},[70,634,81],{"class":80},[70,636,637],{"class":80}," migrate",[70,639,641],{"class":640},"sBjJW"," --seed\n",[10,643,644],{},"We recreate the database because, until now, tests have used an in-memory SQLite database. The local database still contains the original scaffolded users table rather than the version we customized for GitHub authentication.",[406,646,647],{"start":141},[409,648,649,650,415,653,23,656,659],{},"Set ",[67,651,652],{},"APP_FRONTEND_URL",[67,654,655],{},".env",[67,657,658],{},".env.example"," to the frontend's development URL:",[59,661,665],{"className":662,"code":663,"filename":655,"language":664,"meta":65,"style":65},"language-ini shiki shiki-themes github-light github-light github-dark","APP_FRONTEND_URL=http:\u002F\u002Flocalhost:5173\n","ini",[67,666,667],{"__ignoreMap":65},[70,668,669],{"class":72,"line":73},[70,670,663],{},[10,672,673,674,677],{},"Until now, it pointed to ",[67,675,676],{},"http:\u002F\u002Flocalhost:4173",", the VitePress preview server.",[42,679,681],{"id":680},"connecting-to-the-backend-from-the-frontend","Connecting to the backend from the frontend",[10,683,684],{},"In this section, we will make the first requests from the frontend and verify that the connection works.",[34,686,689],{"color":687,"icon":688},"warning","i-ph-warning-duotone",[10,690,691],{},"This is not the final version of the code. We will improve it in the next article.",[693,694,696],"h3",{"id":695},"social-authentication","Social authentication",[10,698,699,700,703],{},"The first feature we can test is social authentication. We will add a header button that links to ",[67,701,702],{},"\u002Fauth\u002Fgithub\u002Fredirect"," on the backend. Because the backend URL will differ between development and production, we will store its base URL in an environment variable. The user will then be redirected to GitHub and, after authorizing the application, back to the frontend.",[10,705,706,707,710],{},"For the environment variable, we can use the ",[67,708,709],{},"VITE_"," prefix to expose it to the frontend:",[59,712,715],{"className":662,"code":713,"filename":714,"language":664,"meta":65,"style":65},"VITE_API_URL=http:\u002F\u002Flocalhost:8000\n","src\u002F.env",[67,716,717],{"__ignoreMap":65},[70,718,719],{"class":72,"line":73},[70,720,713],{},[34,722,723],{"color":36,"icon":37},[10,724,725,726,728],{},"You can safely add this variable to the ",[67,727,658],{}," file.",[10,730,731],{},"Now add the button to the header:",[59,733,738],{"className":734,"code":735,"filename":736,"language":737,"meta":65,"style":65},"language-vue shiki shiki-themes github-light github-light github-dark has-diff","\u003Cscript lang=\"ts\" setup>\n\u002F\u002F ...\n\nconst loginUrl = `${import.meta.env.VITE_API_URL}\u002Fauth\u002Fgithub\u002Fredirect` \u002F\u002F [!code ++]\n\u003C\u002Fscript>\n\n\u003Ctemplate>\n  \u003Cheader class=\"border-b-4 border-black bg-white p-8\">\n    \u003C!-- ... -->\n\n    \u003Cdiv class=\"flex items-center gap-6\">\n      \u003C!-- ... -->\n\n      \u003CButton :href=\"loginUrl\" label=\"Login\" \u002F> \u003C!-- [!code ++] -->\n    \u003C\u002Fdiv>\n  \u003C\u002Fheader>\n\u003C\u002Ftemplate>\n",".vitepress\u002Ftheme\u002Fcommon\u002Fcomponents\u002FTheHeader.vue","vue",[67,739,740,764,769,773,813,822,826,835,853,858,862,879,884,888,924,933,942],{"__ignoreMap":65},[70,741,742,745,749,752,755,758,761],{"class":72,"line":73},[70,743,744],{"class":622},"\u003C",[70,746,748],{"class":747},"sovSZ","script",[70,750,751],{"class":76}," lang",[70,753,754],{"class":622},"=",[70,756,757],{"class":80},"\"ts\"",[70,759,760],{"class":76}," setup",[70,762,763],{"class":622},">\n",[70,765,766],{"class":72,"line":128},[70,767,483],{"class":768},"sCsY4",[70,770,771],{"class":72,"line":135},[70,772,132],{"emptyLinePlaceholder":131},[70,774,778,782,785,788,791,794,797,800,802,805,807,810],{"class":775,"line":141},[72,776,777],"diff","add",[70,779,781],{"class":780},"s8jYJ","const",[70,783,784],{"class":640}," loginUrl",[70,786,787],{"class":780}," =",[70,789,790],{"class":80}," `${",[70,792,793],{"class":780},"import",[70,795,796],{"class":80},".",[70,798,799],{"class":640},"meta",[70,801,796],{"class":80},[70,803,804],{"class":622},"env",[70,806,796],{"class":80},[70,808,809],{"class":640},"VITE_API_URL",[70,811,812],{"class":80},"}\u002Fauth\u002Fgithub\u002Fredirect`",[70,814,815,818,820],{"class":72,"line":146},[70,816,817],{"class":622},"\u003C\u002F",[70,819,748],{"class":747},[70,821,763],{"class":622},[70,823,824],{"class":72,"line":152},[70,825,132],{"emptyLinePlaceholder":131},[70,827,828,830,833],{"class":72,"line":158},[70,829,744],{"class":622},[70,831,832],{"class":747},"template",[70,834,763],{"class":622},[70,836,837,840,843,846,848,851],{"class":72,"line":163},[70,838,839],{"class":622},"  \u003C",[70,841,842],{"class":747},"header",[70,844,845],{"class":76}," class",[70,847,754],{"class":622},[70,849,850],{"class":80},"\"border-b-4 border-black bg-white p-8\"",[70,852,763],{"class":622},[70,854,855],{"class":72,"line":169},[70,856,857],{"class":768},"    \u003C!-- ... -->\n",[70,859,860],{"class":72,"line":174},[70,861,132],{"emptyLinePlaceholder":131},[70,863,864,867,870,872,874,877],{"class":72,"line":180},[70,865,866],{"class":622},"    \u003C",[70,868,869],{"class":747},"div",[70,871,845],{"class":76},[70,873,754],{"class":622},[70,875,876],{"class":80},"\"flex items-center gap-6\"",[70,878,763],{"class":622},[70,880,881],{"class":72,"line":186},[70,882,883],{"class":768},"      \u003C!-- ... -->\n",[70,885,886],{"class":72,"line":192},[70,887,132],{"emptyLinePlaceholder":131},[70,889,891,894,897,900,903,905,908,911,913,916,918,921],{"class":890,"line":197},[72,776,777],[70,892,893],{"class":622},"      \u003C",[70,895,896],{"class":747},"Button",[70,898,899],{"class":622}," :",[70,901,902],{"class":76},"href",[70,904,754],{"class":622},[70,906,907],{"class":80},"\"",[70,909,910],{"class":622},"loginUrl",[70,912,907],{"class":80},[70,914,915],{"class":76}," label",[70,917,754],{"class":622},[70,919,920],{"class":80},"\"Login\"",[70,922,923],{"class":622}," \u002F> ",[70,925,926,929,931],{"class":72,"line":203},[70,927,928],{"class":622},"    \u003C\u002F",[70,930,869],{"class":747},[70,932,763],{"class":622},[70,934,935,938,940],{"class":72,"line":208},[70,936,937],{"class":622},"  \u003C\u002F",[70,939,842],{"class":747},[70,941,763],{"class":622},[70,943,944,946,948],{"class":72,"line":214},[70,945,817],{"class":622},[70,947,832],{"class":747},[70,949,763],{"class":622},[10,951,952,953,955,956,958,959,961,962,796],{},"We use ",[67,954,809],{}," to build the login URL. When Vite starts, it loads ",[67,957,714],{}," and exposes variables prefixed with ",[67,960,709],{}," through ",[67,963,964],{},"import.meta.env",[10,966,967],{},"We can also add types for this object to improve the development experience.",[406,969,970],{},[409,971,972,973,976],{},"Create a ",[67,974,975],{},"vite-env.d.ts"," file in the root of the project:",[59,978,982],{"className":979,"code":980,"filename":975,"language":981,"meta":65,"style":65},"language-ts shiki shiki-themes github-light github-light github-dark","\u002F\u002F\u002F \u003Creference types=\"vite\u002Fclient\" \u002F>\n\ninterface ImportMetaEnv {\n  readonly VITE_API_URL: string\n}\n\ninterface ImportMeta {\n  readonly env: ImportMetaEnv\n}\n","ts",[67,983,984,1003,1007,1018,1033,1037,1041,1050,1062],{"__ignoreMap":65},[70,985,986,989,992,995,997,1000],{"class":72,"line":73},[70,987,988],{"class":768},"\u002F\u002F\u002F \u003C",[70,990,991],{"class":747},"reference",[70,993,994],{"class":76}," types",[70,996,754],{"class":780},[70,998,999],{"class":80},"\"vite\u002Fclient\"",[70,1001,1002],{"class":768}," \u002F>\n",[70,1004,1005],{"class":72,"line":128},[70,1006,132],{"emptyLinePlaceholder":131},[70,1008,1009,1012,1015],{"class":72,"line":135},[70,1010,1011],{"class":780},"interface",[70,1013,1014],{"class":76}," ImportMetaEnv",[70,1016,1017],{"class":622}," {\n",[70,1019,1020,1023,1027,1030],{"class":72,"line":141},[70,1021,1022],{"class":780},"  readonly",[70,1024,1026],{"class":1025},"sP4rz"," VITE_API_URL",[70,1028,1029],{"class":780},":",[70,1031,1032],{"class":640}," string\n",[70,1034,1035],{"class":72,"line":146},[70,1036,469],{"class":622},[70,1038,1039],{"class":72,"line":152},[70,1040,132],{"emptyLinePlaceholder":131},[70,1042,1043,1045,1048],{"class":72,"line":158},[70,1044,1011],{"class":780},[70,1046,1047],{"class":76}," ImportMeta",[70,1049,1017],{"class":622},[70,1051,1052,1054,1057,1059],{"class":72,"line":163},[70,1053,1022],{"class":780},[70,1055,1056],{"class":1025}," env",[70,1058,1029],{"class":780},[70,1060,1061],{"class":76}," ImportMetaEnv\n",[70,1063,1064],{"class":72,"line":169},[70,1065,469],{"class":622},[406,1067,1068],{"start":128},[409,1069,1070],{},"Install Vite as a dev dependency:",[59,1072,1074],{"className":61,"code":1073,"filename":63,"language":64,"meta":65,"style":65},"npm install -D vite\n",[67,1075,1076],{"__ignoreMap":65},[70,1077,1078,1081,1084,1087],{"class":72,"line":73},[70,1079,1080],{"class":76},"npm",[70,1082,1083],{"class":80}," install",[70,1085,1086],{"class":640}," -D",[70,1088,1089],{"class":80}," vite\n",[34,1091,1092],{"color":263,"icon":264},[10,1093,1094],{},"The package manager pnpm will only make accessible packages that have been directly installed in the project. So even if VitePress uses Vite, we need to install it to have access to the types.",[406,1096,1097],{"start":135},[409,1098,1099,1100,1102,1103,1106],{},"Add the ",[67,1101,975],{}," file to the ",[67,1104,1105],{},"tsconfig.json"," file:",[59,1108,1112],{"className":1109,"code":1110,"filename":1105,"language":1111,"meta":65,"style":65},"language-json shiki shiki-themes github-light github-light github-dark has-highlighted","{\n  \"include\": [\n    \".\u002F.vitepress\u002F**\u002F*\",\n    \"vite-env.d.ts\" \u002F\u002F [!code highlight]\n  ]\n}\n","json",[67,1113,1114,1118,1126,1134,1140,1145],{"__ignoreMap":65},[70,1115,1116],{"class":72,"line":73},[70,1117,435],{"class":622},[70,1119,1120,1123],{"class":72,"line":128},[70,1121,1122],{"class":640},"  \"include\"",[70,1124,1125],{"class":622},": [\n",[70,1127,1128,1131],{"class":72,"line":135},[70,1129,1130],{"class":80},"    \".\u002F.vitepress\u002F**\u002F*\"",[70,1132,1133],{"class":622},",\n",[70,1135,1137],{"class":1136,"line":141},[72,242],[70,1138,1139],{"class":80},"    \"vite-env.d.ts\"",[70,1141,1142],{"class":72,"line":146},[70,1143,1144],{"class":622},"  ]\n",[70,1146,1147],{"class":72,"line":152},[70,1148,469],{"class":622},[10,1150,1151,1152,1154,1155,796],{},"Now ",[67,1153,964],{}," is typed, and TypeScript knows about ",[67,1156,809],{},[1158,1159,1160,1161],"video",{"autoPlay":131,"loop":131,"muted":131,"playsInline":131},"\n  ",[1162,1163],"source",{"src":1164,"type":1165},"https:\u002F\u002Fimages.soubiran.dev\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbridging-the-gap-connecting-your-frontend-and-backend\u002Fsocial-authentication-workflow.mp4","video\u002Fmp4",[10,1167,1168],{},"Clicking the button should redirect us to GitHub for authorization and then back to the frontend. The first connection is working.",[693,1170,1172],{"id":1171},"creating-a-comment","Creating a comment",[10,1174,1175],{},"The second feature we can test is creating a comment. If this works, we can move to the next article with confidence that the backend and frontend can communicate.",[10,1177,1178,1179,1182,1183,1186],{},"To make requests, we will use ",[67,1180,1181],{},"ofetch",". It wraps the native ",[67,1184,1185],{},"fetch"," API and adds JSON body serialization, retries, a base URL, and interceptors.",[59,1188,1190],{"className":61,"code":1189,"filename":63,"language":64,"meta":65,"style":65},"pnpm add ofetch\n",[67,1191,1192],{"__ignoreMap":65},[70,1193,1194,1197,1200],{"class":72,"line":73},[70,1195,1196],{"class":76},"pnpm",[70,1198,1199],{"class":80}," add",[70,1201,1202],{"class":80}," ofetch\n",[10,1204,1205,1206,1209],{},"We will make the first request from ",[67,1207,1208],{},"Layout.vue"," as a temporary test.",[10,1211,1212],{},"First, let's try the basic request:",[59,1214,1218],{"className":1215,"code":1216,"filename":1217,"language":737,"meta":65,"style":65},"language-vue shiki shiki-themes github-light github-light github-dark","\u003Cscript lang=\"ts\" setup>\nimport { ofetch } from 'ofetch'\n\nofetch('\u002Fapi\u002Fposts\u002F1\u002Fcomments', {\n  baseURL: import.meta.env.VITE_API_URL,\n  method: 'POST',\n  body: {\n    content: 'Hello world!',\n  },\n  headers: {\n    Accept: 'application\u002Fjson',\n  }\n})\n\u003C\u002Fscript>\n",".vitepress\u002Ftheme\u002FLayout.vue",[67,1219,1220,1236,1249,1253,1266,1284,1294,1299,1309,1314,1319,1329,1334,1339],{"__ignoreMap":65},[70,1221,1222,1224,1226,1228,1230,1232,1234],{"class":72,"line":73},[70,1223,744],{"class":622},[70,1225,748],{"class":747},[70,1227,751],{"class":76},[70,1229,754],{"class":622},[70,1231,757],{"class":80},[70,1233,760],{"class":76},[70,1235,763],{"class":622},[70,1237,1238,1240,1243,1246],{"class":72,"line":128},[70,1239,793],{"class":780},[70,1241,1242],{"class":622}," { ofetch } ",[70,1244,1245],{"class":780},"from",[70,1247,1248],{"class":80}," 'ofetch'\n",[70,1250,1251],{"class":72,"line":135},[70,1252,132],{"emptyLinePlaceholder":131},[70,1254,1255,1257,1260,1263],{"class":72,"line":141},[70,1256,1181],{"class":76},[70,1258,1259],{"class":622},"(",[70,1261,1262],{"class":80},"'\u002Fapi\u002Fposts\u002F1\u002Fcomments'",[70,1264,1265],{"class":622},", {\n",[70,1267,1268,1271,1273,1275,1277,1280,1282],{"class":72,"line":146},[70,1269,1270],{"class":622},"  baseURL: ",[70,1272,793],{"class":780},[70,1274,796],{"class":622},[70,1276,799],{"class":640},[70,1278,1279],{"class":622},".env.",[70,1281,809],{"class":640},[70,1283,1133],{"class":622},[70,1285,1286,1289,1292],{"class":72,"line":152},[70,1287,1288],{"class":622},"  method: ",[70,1290,1291],{"class":80},"'POST'",[70,1293,1133],{"class":622},[70,1295,1296],{"class":72,"line":158},[70,1297,1298],{"class":622},"  body: {\n",[70,1300,1301,1304,1307],{"class":72,"line":163},[70,1302,1303],{"class":622},"    content: ",[70,1305,1306],{"class":80},"'Hello world!'",[70,1308,1133],{"class":622},[70,1310,1311],{"class":72,"line":169},[70,1312,1313],{"class":622},"  },\n",[70,1315,1316],{"class":72,"line":174},[70,1317,1318],{"class":622},"  headers: {\n",[70,1320,1321,1324,1327],{"class":72,"line":180},[70,1322,1323],{"class":622},"    Accept: ",[70,1325,1326],{"class":80},"'application\u002Fjson'",[70,1328,1133],{"class":622},[70,1330,1331],{"class":72,"line":186},[70,1332,1333],{"class":622},"  }\n",[70,1335,1336],{"class":72,"line":192},[70,1337,1338],{"class":622},"})\n",[70,1340,1341,1343,1345],{"class":72,"line":197},[70,1342,817],{"class":622},[70,1344,748],{"class":747},[70,1346,763],{"class":622},[10,1348,1349,1350,1353],{},"This request looks sufficient, but inspecting the browser's network tab shows a ",[67,1351,1352],{},"419"," response. The response preview contains:",[59,1355,1359],{"className":1356,"code":1357,"filename":1358,"language":1111,"meta":65,"style":65},"language-json shiki shiki-themes github-light github-light github-dark","{\n  \"message\": \"CSRF token mismatch.\"\n  \u002F\u002F ...\n}\n","Example",[67,1360,1361,1365,1376,1380],{"__ignoreMap":65},[70,1362,1363],{"class":72,"line":73},[70,1364,435],{"class":622},[70,1366,1367,1370,1373],{"class":72,"line":128},[70,1368,1369],{"class":640},"  \"message\"",[70,1371,1372],{"class":622},": ",[70,1374,1375],{"class":80},"\"CSRF token mismatch.\"\n",[70,1377,1378],{"class":72,"line":135},[70,1379,315],{"class":768},[70,1381,1382],{"class":72,"line":141},[70,1383,469],{"class":622},[10,1385,1386],{},"The error is explicit: the request needs a CSRF token.",[10,1388,1389],{},"What is a CSRF token, and how do we handle it in an SPA?",[10,1391,1392],{},"A CSRF token helps prevent Cross-Site Request Forgery attacks. It gives the server a way to verify that a state-changing request comes from our application rather than from a malicious site acting on behalf of an authenticated user. In a server-rendered application, the token is embedded in the HTML. In an SPA, we need to retrieve and send it separately.",[10,1394,1395,1396,1399],{},"Laravel stores the token in the session and also places an encrypted value in a cookie that JavaScript on our site can read. We send that value in the ",[67,1397,1398],{},"X-XSRF-TOKEN"," header, and Laravel verifies it against the session.",[34,1401,1402],{"color":263,"icon":264},[10,1403,1404],{},"We cannot trust the cookie alone because the browser automatically sends it with requests. The explicit header is what proves that our JavaScript intentionally included the token.",[10,1406,1407],{},"Add the CSRF token to the request:",[59,1409,1411],{"className":1215,"code":1410,"filename":1217,"language":737,"meta":65,"style":65},"\u003Cscript lang=\"ts\" setup>\nimport { ofetch } from 'ofetch'\n\nfunction getCookie(name: string) {\n  const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`))\n  return match ? match[2] : null\n}\n\nofetch('\u002Fapi\u002Fposts\u002F1\u002Fcomments', {\n  \u002F\u002F ...\n  onRequest: async ({ options }) => {\n    const method = options.method?.toUpperCase() || 'GET'\n\n    if (['GET', 'HEAD', 'OPTIONS'].includes(method)) {\n      return\n    }\n\n    const xsrfToken = getCookie('XSRF-TOKEN')\n\n    if (!xsrfToken) {\n      await ofetch('\u002Fsanctum\u002Fcsrf-cookie', {\n        baseURL: import.meta.env.VITE_API_URL,\n        credentials: 'include',\n      })\n    }\n\n    options.headers.set('X-Xsrf-Token', decodeURIComponent(getCookie('XSRF-TOKEN') || ''))\n  },\n})\n\u003C\u002Fscript>\n",[67,1412,1413,1429,1439,1443,1464,1501,1526,1530,1534,1544,1548,1572,1597,1601,1632,1637,1641,1645,1664,1668,1681,1696,1713,1723,1728,1733,1738,1776,1781,1786],{"__ignoreMap":65},[70,1414,1415,1417,1419,1421,1423,1425,1427],{"class":72,"line":73},[70,1416,744],{"class":622},[70,1418,748],{"class":747},[70,1420,751],{"class":76},[70,1422,754],{"class":622},[70,1424,757],{"class":80},[70,1426,760],{"class":76},[70,1428,763],{"class":622},[70,1430,1431,1433,1435,1437],{"class":72,"line":128},[70,1432,793],{"class":780},[70,1434,1242],{"class":622},[70,1436,1245],{"class":780},[70,1438,1248],{"class":80},[70,1440,1441],{"class":72,"line":135},[70,1442,132],{"emptyLinePlaceholder":131},[70,1444,1445,1448,1451,1453,1456,1458,1461],{"class":72,"line":141},[70,1446,1447],{"class":780},"function",[70,1449,1450],{"class":76}," getCookie",[70,1452,1259],{"class":622},[70,1454,1455],{"class":1025},"name",[70,1457,1029],{"class":780},[70,1459,1460],{"class":640}," string",[70,1462,1463],{"class":622},") {\n",[70,1465,1466,1469,1472,1474,1477,1480,1482,1485,1488,1490,1493,1495,1498],{"class":72,"line":146},[70,1467,1468],{"class":780},"  const",[70,1470,1471],{"class":640}," match",[70,1473,787],{"class":780},[70,1475,1476],{"class":622}," document.cookie.",[70,1478,1479],{"class":76},"match",[70,1481,1259],{"class":622},[70,1483,1484],{"class":780},"new",[70,1486,1487],{"class":76}," RegExp",[70,1489,1259],{"class":622},[70,1491,1492],{"class":80},"`(^| )${",[70,1494,1455],{"class":622},[70,1496,1497],{"class":80},"}=([^;]+)`",[70,1499,1500],{"class":622},"))\n",[70,1502,1503,1506,1509,1512,1515,1518,1521,1523],{"class":72,"line":152},[70,1504,1505],{"class":780},"  return",[70,1507,1508],{"class":622}," match ",[70,1510,1511],{"class":780},"?",[70,1513,1514],{"class":622}," match[",[70,1516,1517],{"class":640},"2",[70,1519,1520],{"class":622},"] ",[70,1522,1029],{"class":780},[70,1524,1525],{"class":640}," null\n",[70,1527,1528],{"class":72,"line":158},[70,1529,469],{"class":622},[70,1531,1532],{"class":72,"line":163},[70,1533,132],{"emptyLinePlaceholder":131},[70,1535,1536,1538,1540,1542],{"class":72,"line":169},[70,1537,1181],{"class":76},[70,1539,1259],{"class":622},[70,1541,1262],{"class":80},[70,1543,1265],{"class":622},[70,1545,1546],{"class":72,"line":174},[70,1547,315],{"class":768},[70,1549,1550,1553,1555,1558,1561,1564,1567,1570],{"class":72,"line":180},[70,1551,1552],{"class":76},"  onRequest",[70,1554,1372],{"class":622},[70,1556,1557],{"class":780},"async",[70,1559,1560],{"class":622}," ({ ",[70,1562,1563],{"class":1025},"options",[70,1565,1566],{"class":622}," }) ",[70,1568,1569],{"class":780},"=>",[70,1571,1017],{"class":622},[70,1573,1574,1577,1580,1582,1585,1588,1591,1594],{"class":72,"line":186},[70,1575,1576],{"class":780},"    const",[70,1578,1579],{"class":640}," method",[70,1581,787],{"class":780},[70,1583,1584],{"class":622}," options.method?.",[70,1586,1587],{"class":76},"toUpperCase",[70,1589,1590],{"class":622},"() ",[70,1592,1593],{"class":780},"||",[70,1595,1596],{"class":80}," 'GET'\n",[70,1598,1599],{"class":72,"line":192},[70,1600,132],{"emptyLinePlaceholder":131},[70,1602,1603,1606,1609,1612,1615,1618,1620,1623,1626,1629],{"class":72,"line":197},[70,1604,1605],{"class":780},"    if",[70,1607,1608],{"class":622}," ([",[70,1610,1611],{"class":80},"'GET'",[70,1613,1614],{"class":622},", ",[70,1616,1617],{"class":80},"'HEAD'",[70,1619,1614],{"class":622},[70,1621,1622],{"class":80},"'OPTIONS'",[70,1624,1625],{"class":622},"].",[70,1627,1628],{"class":76},"includes",[70,1630,1631],{"class":622},"(method)) {\n",[70,1633,1634],{"class":72,"line":203},[70,1635,1636],{"class":780},"      return\n",[70,1638,1639],{"class":72,"line":208},[70,1640,464],{"class":622},[70,1642,1643],{"class":72,"line":214},[70,1644,132],{"emptyLinePlaceholder":131},[70,1646,1647,1649,1652,1654,1656,1658,1661],{"class":72,"line":219},[70,1648,1576],{"class":780},[70,1650,1651],{"class":640}," xsrfToken",[70,1653,787],{"class":780},[70,1655,1450],{"class":76},[70,1657,1259],{"class":622},[70,1659,1660],{"class":80},"'XSRF-TOKEN'",[70,1662,1663],{"class":622},")\n",[70,1665,1666],{"class":72,"line":225},[70,1667,132],{"emptyLinePlaceholder":131},[70,1669,1670,1672,1675,1678],{"class":72,"line":230},[70,1671,1605],{"class":780},[70,1673,1674],{"class":622}," (",[70,1676,1677],{"class":780},"!",[70,1679,1680],{"class":622},"xsrfToken) {\n",[70,1682,1683,1686,1689,1691,1694],{"class":72,"line":236},[70,1684,1685],{"class":780},"      await",[70,1687,1688],{"class":76}," ofetch",[70,1690,1259],{"class":622},[70,1692,1693],{"class":80},"'\u002Fsanctum\u002Fcsrf-cookie'",[70,1695,1265],{"class":622},[70,1697,1698,1701,1703,1705,1707,1709,1711],{"class":72,"line":243},[70,1699,1700],{"class":622},"        baseURL: ",[70,1702,793],{"class":780},[70,1704,796],{"class":622},[70,1706,799],{"class":640},[70,1708,1279],{"class":622},[70,1710,809],{"class":640},[70,1712,1133],{"class":622},[70,1714,1715,1718,1721],{"class":72,"line":249},[70,1716,1717],{"class":622},"        credentials: ",[70,1719,1720],{"class":80},"'include'",[70,1722,1133],{"class":622},[70,1724,1725],{"class":72,"line":254},[70,1726,1727],{"class":622},"      })\n",[70,1729,1731],{"class":72,"line":1730},25,[70,1732,464],{"class":622},[70,1734,1736],{"class":72,"line":1735},26,[70,1737,132],{"emptyLinePlaceholder":131},[70,1739,1741,1744,1747,1749,1752,1754,1757,1759,1762,1764,1766,1769,1771,1774],{"class":72,"line":1740},27,[70,1742,1743],{"class":622},"    options.headers.",[70,1745,1746],{"class":76},"set",[70,1748,1259],{"class":622},[70,1750,1751],{"class":80},"'X-Xsrf-Token'",[70,1753,1614],{"class":622},[70,1755,1756],{"class":76},"decodeURIComponent",[70,1758,1259],{"class":622},[70,1760,1761],{"class":76},"getCookie",[70,1763,1259],{"class":622},[70,1765,1660],{"class":80},[70,1767,1768],{"class":622},") ",[70,1770,1593],{"class":780},[70,1772,1773],{"class":80}," ''",[70,1775,1500],{"class":622},[70,1777,1779],{"class":72,"line":1778},28,[70,1780,1313],{"class":622},[70,1782,1784],{"class":72,"line":1783},29,[70,1785,1338],{"class":622},[70,1787,1789,1791,1793],{"class":72,"line":1788},30,[70,1790,817],{"class":622},[70,1792,748],{"class":747},[70,1794,763],{"class":622},[10,1796,1797,1798,1801],{},"This implementation uses an ofetch interceptor to add the CSRF token automatically. An interceptor is called at a stage in the request lifecycle. Here, ",[67,1799,1800],{},"onRequest"," modifies the outgoing request.",[10,1803,1804],{},"We only need the token for state-changing requests, so we skip safe methods. Adding it to them would not necessarily be harmful, but it could trigger unnecessary work.",[10,1806,1807,1808,1811],{},"Next, we read the token from the cookie. If it does not exist, we call Sanctum's ",[67,1809,1810],{},"\u002Fsanctum\u002Fcsrf-cookie"," endpoint to create it.",[10,1813,1814],{},"Finally, we add the token to the request headers. With this helper in place, the frontend can make state-changing requests without repeating the CSRF setup each time.",[10,1816,1817],{},"We are making this helper complete now because we will reuse it in the next article.",[10,1819,1820,1821,1823],{},"Refresh the page. It still fails with a ",[67,1822,1352],{}," status code. Inspect the request:",[59,1825,1829],{"className":1826,"code":1827,"filename":1358,"language":1828,"meta":65,"style":65},"language-http shiki shiki-themes github-light github-light github-dark","POST \u002Fapi\u002Fposts\u002F1\u002Fcomments HTTP\u002F1.1\nOrigin: http:\u002F\u002Flocalhost:5173\naccept: application\u002Fjson\nx-xsrf-token: eyJpdiI6IktwK1I0UXA3K3F6Y3BvMEdKWHhGblE9PSIsInZhbHVlIjoidlgyMXlSbmlRMjhuNFNhODBLMHdUSkFJSDlQZzhObjJ2VDBIOWd1WjBrMzRZVWdqZldMZWxKcFlDMHB5ajZxZTY5bWR2amJLNTdhTFhtRHJqb3kxZlEvOFptNzdMSmZHU1FmeUw0d0pIRE1DWHRCSmZ1eFJ4aDBhN21qMW5KcDEiLCJtYWMiOiJmYjgyN2E1ZDAxMjMxZWZiZDk4MjU4MzAxOGE4OTYwOWY4ZmM1OGE3ZWMyYzM2Y2FjMTM4YWIwNGVmMDU1M2NhIiwidGFnIjoiIn0=\n","http",[67,1830,1831,1836,1841,1846],{"__ignoreMap":65},[70,1832,1833],{"class":72,"line":73},[70,1834,1835],{},"POST \u002Fapi\u002Fposts\u002F1\u002Fcomments HTTP\u002F1.1\n",[70,1837,1838],{"class":72,"line":128},[70,1839,1840],{},"Origin: http:\u002F\u002Flocalhost:5173\n",[70,1842,1843],{"class":72,"line":135},[70,1844,1845],{},"accept: application\u002Fjson\n",[70,1847,1848],{"class":72,"line":141},[70,1849,1850],{},"x-xsrf-token: eyJpdiI6IktwK1I0UXA3K3F6Y3BvMEdKWHhGblE9PSIsInZhbHVlIjoidlgyMXlSbmlRMjhuNFNhODBLMHdUSkFJSDlQZzhObjJ2VDBIOWd1WjBrMzRZVWdqZldMZWxKcFlDMHB5ajZxZTY5bWR2amJLNTdhTFhtRHJqb3kxZlEvOFptNzdMSmZHU1FmeUw0d0pIRE1DWHRCSmZ1eFJ4aDBhN21qMW5KcDEiLCJtYWMiOiJmYjgyN2E1ZDAxMjMxZWZiZDk4MjU4MzAxOGE4OTYwOWY4ZmM1OGE3ZWMyYzM2Y2FjMTM4YWIwNGVmMDU1M2NhIiwidGFnIjoiIn0=\n",[10,1852,1853,1854,1857,1858,1861],{},"The request contains the ",[67,1855,1856],{},"x-xsrf-token"," header, but no ",[67,1859,1860],{},"cookie"," header. That is a problem because the user is authenticated with a session cookie. Without the cookie, the backend cannot authenticate the user or compare the CSRF token with the session.",[10,1863,1864,1865,1868],{},"To fix this, add ",[67,1866,1867],{},"credentials: 'include'"," to the request. This tells the browser to include cookies on a cross-origin request, which is exactly what we need here.",[59,1870,1872],{"className":734,"code":1871,"filename":1217,"language":737,"meta":65,"style":65},"\u003Cscript lang=\"ts\" setup>\nofetch('\u002Fapi\u002Fposts\u002F1\u002Fcomments', {\n  \u002F\u002F ...\n  credentials: 'include', \u002F\u002F [!code ++]\n})\n\u003C\u002Fscript>\n",[67,1873,1874,1890,1900,1904,1914,1918],{"__ignoreMap":65},[70,1875,1876,1878,1880,1882,1884,1886,1888],{"class":72,"line":73},[70,1877,744],{"class":622},[70,1879,748],{"class":747},[70,1881,751],{"class":76},[70,1883,754],{"class":622},[70,1885,757],{"class":80},[70,1887,760],{"class":76},[70,1889,763],{"class":622},[70,1891,1892,1894,1896,1898],{"class":72,"line":128},[70,1893,1181],{"class":76},[70,1895,1259],{"class":622},[70,1897,1262],{"class":80},[70,1899,1265],{"class":622},[70,1901,1902],{"class":72,"line":135},[70,1903,315],{"class":768},[70,1905,1907,1910,1912],{"class":1906,"line":141},[72,776,777],[70,1908,1909],{"class":622},"  credentials: ",[70,1911,1720],{"class":80},[70,1913,1614],{"class":622},[70,1915,1916],{"class":72,"line":146},[70,1917,1338],{"class":622},[70,1919,1920,1922,1924],{"class":72,"line":152},[70,1921,817],{"class":622},[70,1923,748],{"class":747},[70,1925,763],{"class":622},[10,1927,1928],{},"Now the request works. 🎉",[42,1930,1932],{"id":1931},"final-thoughts","Final thoughts",[10,1934,1935],{},"The connection is now working end to end. The frontend can call Laravel across origins, obtain a CSRF token when needed, and include the session cookie required for authenticated requests.",[10,1937,1938,1939,1944],{},"This setup gives us a reusable API foundation rather than a one-off request. Next, we will build a shared authentication layer with ",[17,1940,1943],{"href":1941,"rel":1942},"https:\u002F\u002Fpinia-colada.esm.dev\u002F",[21],"Pinia Colada"," so components can react to the current user and logout without duplicating request logic.",[1946,1947,1948],"style",{},"html pre.shiki code .snPdu, html code.shiki .snPdu{--shiki-light:#6F42C1;--shiki-default:#6F42C1;--shiki-dark:#B392F0}html pre.shiki code .sIIMD, html code.shiki .sIIMD{--shiki-light:#032F62;--shiki-default:#032F62;--shiki-dark:#9ECBFF}html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .sxrX7, html code.shiki .sxrX7{--shiki-light:#24292E;--shiki-default:#24292E;--shiki-dark:#E1E4E8}html pre.shiki code .sBjJW, html code.shiki .sBjJW{--shiki-light:#005CC5;--shiki-default:#005CC5;--shiki-dark:#79B8FF}html pre.shiki code .sovSZ, html code.shiki .sovSZ{--shiki-light:#22863A;--shiki-default:#22863A;--shiki-dark:#85E89D}html pre.shiki code .sCsY4, html code.shiki .sCsY4{--shiki-light:#6A737D;--shiki-default:#6A737D;--shiki-dark:#6A737D}html pre.shiki code .s8jYJ, html code.shiki .s8jYJ{--shiki-light:#D73A49;--shiki-default:#D73A49;--shiki-dark:#F97583}html pre.shiki code .sP4rz, html code.shiki .sP4rz{--shiki-light:#E36209;--shiki-default:#E36209;--shiki-dark:#FFAB70}",{"title":65,"searchDepth":128,"depth":128,"links":1950},[1951,1952,1956],{"id":44,"depth":128,"text":45},{"id":680,"depth":128,"text":681,"children":1953},[1954,1955],{"id":695,"depth":135,"text":696},{"id":1171,"depth":135,"text":1172},{"id":1931,"depth":128,"text":1932},"e6040e0a-4997-40d6-bde8-332cbca0f307","2025-02-25","Connect a VitePress frontend to a Laravel API with Sanctum, CORS, CSRF protection, shared credentials, and a reusable API client.","md",null,{},"\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbridging-the-gap-connecting-your-frontend-and-backend","---\ncontentId: e6040e0a-4997-40d6-bde8-332cbca0f307\npart: 6\ntitle: \"Bridging the Gap: Connecting Your Frontend and Backend\"\ndescription: Connect a VitePress frontend to a Laravel API with Sanctum, CORS, CSRF protection, shared credentials, and a reusable API client.\ndate: 2025-02-25\nseriesSlug: empower-and-dynamize-our-vitepress-blog-with-a-laravel-api\n---\n\nWith post synchronization in place, the next step is to connect the VitePress site to the Laravel API.\n\nBecause the two applications will be deployed separately, this involves more than sending a request to a URL. We need to configure [CORS (Cross-Origin Resource Sharing)](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FCross-origin_resource_sharing) and [CSRF (Cross-Site Request Forgery)](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FCross-site_request_forgery) protection, then ensure that the browser sends the credentials Laravel needs for session-based authentication.\n\nThe configuration can feel intimidating at first, but we will handle it one piece at a time. Laravel provides most of the pieces we need.\n\n::callout{icon=\"i-ph-lightbulb-duotone\" color=\"success\"}\nI recommend reading the linked articles if you want a deeper explanation of these concepts. It will make the configuration in this article easier to understand.\n::\n\n## Installing Laravel Sanctum\n\nThe Laravel ecosystem provides [Sanctum](https:\u002F\u002Flaravel.com\u002Fdocs\u002F12.x\u002Fsanctum#spa-authentication), which supports both API tokens and cookie-based authentication for Single Page Applications (SPAs).\n\nTo get started, let's install Sanctum:\n\n```bash [terminal]\nphp artisan install:api\n```\n\nThen, let's publish the cors configuration file:\n\n```bash [terminal]\nphp artisan config:publish cors\n```\n\nCORS, or Cross-Origin Resource Sharing, is a browser security mechanism. By default, browsers prevent a page from making requests to a different origin. This protects users from malicious sites making unauthorized requests on their behalf.\n\nOur frontend needs to communicate with an API hosted on another origin, so we must explicitly allow that origin in the API configuration.\n\nSpeaking of which, let's configure CORS to allow requests from our frontend:\n\n```php [config\u002Fcors.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nreturn [\n    'paths' => ['api\u002F*', 'sanctum\u002Fcsrf-cookie'],\n\n    'allowed_methods' => ['*'],\n\n    'allowed_origins' => [\n        env('APP_FRONTEND_URL'), \u002F\u002F [!code ++]\n    ],\n\n    'allowed_origins_patterns' => [],\n\n    'allowed_headers' => ['*'],\n\n    'exposed_headers' => [],\n\n    'max_age' => 0,\n\n    'supports_credentials' => true, \u002F\u002F [!code highlight]\n\n];\n```\n\nWe will discuss deployment later, but remember that we are creating two applications: the blog and the API that enriches it. They will be deployed separately, which is why the API must allow requests from the blog.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nWe could deploy both applications behind the same domain with a reverse proxy, but that would add complexity that we do not need here.\n::\n\nThen, we need to configure Sanctum to allow requests from our frontend:\n\n```php [config\u002Fsanctum.php]\nreturn [\n    'stateful' => explode(',', (string) env('SANCTUM_STATEFUL_DOMAINS', sprintf(\n        '%s%s',\n        'localhost:4173,localhost:5173', \u002F\u002F [!code highlight]\n        Sanctum::currentApplicationUrlWithPort()\n    ))),\n\n  \u002F\u002F ...\n]\n```\n\nThe important change is adding the frontend's development origins to Sanctum's stateful domains.\n\nA browser origin combines the protocol, hostname, and port. During development, `localhost:5173` and `localhost:8000` are different origins even though they share the same hostname.\n\nThen, we need to add a middleware:\n\n```php [bootstrap\u002Fapp.php]\nreturn Application::configure(basePath: dirname(__DIR__))\n    ->withMiddleware(function (Middleware $middleware): void {\n        $middleware->statefulApi(); \u002F\u002F [!code ++]\n    })\n     ->create();\n```\n\nThis middleware tells Sanctum to authenticate requests with Laravel's session cookie instead of an API token. That is the approach we will use from the frontend.\n\nFinally, we need to change our authentication middleware in the `routes\u002Fapi.php` file. Actually, we use the default Laravel middleware which ensure that requests respect the Sanctum configuration like the stateful domains.\n\n```php [routes\u002Fapi.php]\nRoute::middleware('auth:sanctum')->group(function () { \u002F\u002F [!code highlight]\n    \u002F\u002F Handle authenticated requests...\n});\n```\n\nOur backend is now ready to accept requests from the frontend.\n\nBefore moving to the frontend, finish a few backend changes.\n\n1. Update `store` in `RegisteredViaGitHubController` so it redirects the user to the frontend:\n\n```php [app\u002FHttp\u002FControllers\u002FRegisteredViaGitHubController.php]\nfinal class RegisteredViaGitHubController extends Controller\n{\n    public function store(): RedirectResponse\n    {\n        \u002F\u002F ...\n\n        return redirect(Config::get('app.frontend_url'));\n    }\n}\n```\n\nUpdate its test as well:\n\n```php [tests\u002FHttp\u002FRegisteredViaGitHub\u002FStoreTest.php]\n\u002F\u002F ...\n\ntest('redirects to the frontend', function () {\n    fakeGitHubUser();\n\n    $this->get(route('auth.github.callback'))\n        ->assertRedirect(config('app.frontend_url')); \u002F\u002F [!code highlight]\n});\n\n\u002F\u002F ...\n```\n\n2. Add a database seeder that generates sample comments:\n\n::callout{icon=\"i-ph-lightbulb-duotone\" color=\"success\"}\nRemove the existing contents of the seeder's `run` method before adding this code.\n::\n\n```php [database\u002Fseeders\u002FDatabaseSeeder.php]\nuse App\\Models\\Post;\n\nfinal class DatabaseSeeder extends Seeder\n{\n    public function run(): void\n    {\n        Post::factory()\n            ->count(10)\n            ->hasComments(5)\n            ->create();\n    }\n}\n```\n\nThis creates 10 posts with five comments each, giving us data to use while testing the frontend.\n\n3. Recreate the database and run the migrations:\n\n```bash [terminal]\nrm database\u002Fdatabase.sqlite && touch database\u002Fdatabase.sqlite && php artisan migrate --seed\n```\n\nWe recreate the database because, until now, tests have used an in-memory SQLite database. The local database still contains the original scaffolded users table rather than the version we customized for GitHub authentication.\n\n4. Set `APP_FRONTEND_URL` in `.env` and `.env.example` to the frontend's development URL:\n\n```ini [.env]\nAPP_FRONTEND_URL=http:\u002F\u002Flocalhost:5173\n```\n\nUntil now, it pointed to `http:\u002F\u002Flocalhost:4173`, the VitePress preview server.\n\n## Connecting to the backend from the frontend\n\nIn this section, we will make the first requests from the frontend and verify that the connection works.\n\n::callout{icon=\"i-ph-warning-duotone\" color=\"warning\"}\nThis is not the final version of the code. We will improve it in the next article.\n::\n\n### Social authentication\n\nThe first feature we can test is social authentication. We will add a header button that links to `\u002Fauth\u002Fgithub\u002Fredirect` on the backend. Because the backend URL will differ between development and production, we will store its base URL in an environment variable. The user will then be redirected to GitHub and, after authorizing the application, back to the frontend.\n\nFor the environment variable, we can use the `VITE_` prefix to expose it to the frontend:\n\n```ini [src\u002F.env]\nVITE_API_URL=http:\u002F\u002Flocalhost:8000\n```\n\n::callout{icon=\"i-ph-lightbulb-duotone\" color=\"success\"}\nYou can safely add this variable to the `.env.example` file.\n::\n\nNow add the button to the header:\n\n```vue [.vitepress\u002Ftheme\u002Fcommon\u002Fcomponents\u002FTheHeader.vue]\n\u003Cscript lang=\"ts\" setup>\n\u002F\u002F ...\n\nconst loginUrl = `${import.meta.env.VITE_API_URL}\u002Fauth\u002Fgithub\u002Fredirect` \u002F\u002F [!code ++]\n\u003C\u002Fscript>\n\n\u003Ctemplate>\n  \u003Cheader class=\"border-b-4 border-black bg-white p-8\">\n    \u003C!-- ... -->\n\n    \u003Cdiv class=\"flex items-center gap-6\">\n      \u003C!-- ... -->\n\n      \u003CButton :href=\"loginUrl\" label=\"Login\" \u002F> \u003C!-- [!code ++] -->\n    \u003C\u002Fdiv>\n  \u003C\u002Fheader>\n\u003C\u002Ftemplate>\n```\n\nWe use `VITE_API_URL` to build the login URL. When Vite starts, it loads `src\u002F.env` and exposes variables prefixed with `VITE_` through `import.meta.env`.\n\nWe can also add types for this object to improve the development experience.\n\n1. Create a `vite-env.d.ts` file in the root of the project:\n\n```ts [vite-env.d.ts]\n\u002F\u002F\u002F \u003Creference types=\"vite\u002Fclient\" \u002F>\n\ninterface ImportMetaEnv {\n  readonly VITE_API_URL: string\n}\n\ninterface ImportMeta {\n  readonly env: ImportMetaEnv\n}\n```\n\n2. Install Vite as a dev dependency:\n\n```bash [terminal]\nnpm install -D vite\n```\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nThe package manager pnpm will only make accessible packages that have been directly installed in the project. So even if VitePress uses Vite, we need to install it to have access to the types.\n::\n\n3. Add the `vite-env.d.ts` file to the `tsconfig.json` file:\n\n```json [tsconfig.json]\n{\n  \"include\": [\n    \".\u002F.vitepress\u002F**\u002F*\",\n    \"vite-env.d.ts\" \u002F\u002F [!code highlight]\n  ]\n}\n```\n\nNow `import.meta.env` is typed, and TypeScript knows about `VITE_API_URL`.\n\n\u003Cvideo autoplay loop muted playsinline>\n  \u003Csource src=\"https:\u002F\u002Fimages.soubiran.dev\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbridging-the-gap-connecting-your-frontend-and-backend\u002Fsocial-authentication-workflow.mp4\" type=\"video\u002Fmp4\">\n\u003C\u002Fvideo>\n\nClicking the button should redirect us to GitHub for authorization and then back to the frontend. The first connection is working.\n\n### Creating a comment\n\nThe second feature we can test is creating a comment. If this works, we can move to the next article with confidence that the backend and frontend can communicate.\n\nTo make requests, we will use `ofetch`. It wraps the native `fetch` API and adds JSON body serialization, retries, a base URL, and interceptors.\n\n```bash [terminal]\npnpm add ofetch\n```\n\nWe will make the first request from `Layout.vue` as a temporary test.\n\nFirst, let's try the basic request:\n\n```vue [.vitepress\u002Ftheme\u002FLayout.vue]\n\u003Cscript lang=\"ts\" setup>\nimport { ofetch } from 'ofetch'\n\nofetch('\u002Fapi\u002Fposts\u002F1\u002Fcomments', {\n  baseURL: import.meta.env.VITE_API_URL,\n  method: 'POST',\n  body: {\n    content: 'Hello world!',\n  },\n  headers: {\n    Accept: 'application\u002Fjson',\n  }\n})\n\u003C\u002Fscript>\n```\n\nThis request looks sufficient, but inspecting the browser's network tab shows a `419` response. The response preview contains:\n\n```json [Example]\n{\n  \"message\": \"CSRF token mismatch.\"\n  \u002F\u002F ...\n}\n```\n\nThe error is explicit: the request needs a CSRF token.\n\nWhat is a CSRF token, and how do we handle it in an SPA?\n\nA CSRF token helps prevent Cross-Site Request Forgery attacks. It gives the server a way to verify that a state-changing request comes from our application rather than from a malicious site acting on behalf of an authenticated user. In a server-rendered application, the token is embedded in the HTML. In an SPA, we need to retrieve and send it separately.\n\nLaravel stores the token in the session and also places an encrypted value in a cookie that JavaScript on our site can read. We send that value in the `X-XSRF-TOKEN` header, and Laravel verifies it against the session.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nWe cannot trust the cookie alone because the browser automatically sends it with requests. The explicit header is what proves that our JavaScript intentionally included the token.\n::\n\nAdd the CSRF token to the request:\n\n```vue [.vitepress\u002Ftheme\u002FLayout.vue]\n\u003Cscript lang=\"ts\" setup>\nimport { ofetch } from 'ofetch'\n\nfunction getCookie(name: string) {\n  const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`))\n  return match ? match[2] : null\n}\n\nofetch('\u002Fapi\u002Fposts\u002F1\u002Fcomments', {\n  \u002F\u002F ...\n  onRequest: async ({ options }) => {\n    const method = options.method?.toUpperCase() || 'GET'\n\n    if (['GET', 'HEAD', 'OPTIONS'].includes(method)) {\n      return\n    }\n\n    const xsrfToken = getCookie('XSRF-TOKEN')\n\n    if (!xsrfToken) {\n      await ofetch('\u002Fsanctum\u002Fcsrf-cookie', {\n        baseURL: import.meta.env.VITE_API_URL,\n        credentials: 'include',\n      })\n    }\n\n    options.headers.set('X-Xsrf-Token', decodeURIComponent(getCookie('XSRF-TOKEN') || ''))\n  },\n})\n\u003C\u002Fscript>\n```\n\nThis implementation uses an ofetch interceptor to add the CSRF token automatically. An interceptor is called at a stage in the request lifecycle. Here, `onRequest` modifies the outgoing request.\n\nWe only need the token for state-changing requests, so we skip safe methods. Adding it to them would not necessarily be harmful, but it could trigger unnecessary work.\n\nNext, we read the token from the cookie. If it does not exist, we call Sanctum's `\u002Fsanctum\u002Fcsrf-cookie` endpoint to create it.\n\nFinally, we add the token to the request headers. With this helper in place, the frontend can make state-changing requests without repeating the CSRF setup each time.\n\nWe are making this helper complete now because we will reuse it in the next article.\n\nRefresh the page. It still fails with a `419` status code. Inspect the request:\n\n```http [Example]\nPOST \u002Fapi\u002Fposts\u002F1\u002Fcomments HTTP\u002F1.1\nOrigin: http:\u002F\u002Flocalhost:5173\naccept: application\u002Fjson\nx-xsrf-token: eyJpdiI6IktwK1I0UXA3K3F6Y3BvMEdKWHhGblE9PSIsInZhbHVlIjoidlgyMXlSbmlRMjhuNFNhODBLMHdUSkFJSDlQZzhObjJ2VDBIOWd1WjBrMzRZVWdqZldMZWxKcFlDMHB5ajZxZTY5bWR2amJLNTdhTFhtRHJqb3kxZlEvOFptNzdMSmZHU1FmeUw0d0pIRE1DWHRCSmZ1eFJ4aDBhN21qMW5KcDEiLCJtYWMiOiJmYjgyN2E1ZDAxMjMxZWZiZDk4MjU4MzAxOGE4OTYwOWY4ZmM1OGE3ZWMyYzM2Y2FjMTM4YWIwNGVmMDU1M2NhIiwidGFnIjoiIn0=\n```\n\nThe request contains the `x-xsrf-token` header, but no `cookie` header. That is a problem because the user is authenticated with a session cookie. Without the cookie, the backend cannot authenticate the user or compare the CSRF token with the session.\n\nTo fix this, add `credentials: 'include'` to the request. This tells the browser to include cookies on a cross-origin request, which is exactly what we need here.\n\n```vue [.vitepress\u002Ftheme\u002FLayout.vue]\n\u003Cscript lang=\"ts\" setup>\nofetch('\u002Fapi\u002Fposts\u002F1\u002Fcomments', {\n  \u002F\u002F ...\n  credentials: 'include', \u002F\u002F [!code ++]\n})\n\u003C\u002Fscript>\n```\n\nNow the request works. 🎉\n\n## Final thoughts\n\nThe connection is now working end to end. The frontend can call Laravel across origins, obtain a CSRF token when needed, and include the session cookie required for authenticated requests.\n\nThis setup gives us a reusable API foundation rather than a one-off request. Next, we will build a shared authentication layer with [Pinia Colada](https:\u002F\u002Fpinia-colada.esm.dev\u002F) so components can react to the current user and logout without duplicating request logic.\n",{"title":5,"description":1959},"empower-and-dynamize-our-vitepress-blog-with-a-laravel-api",{"loc":1963},"series\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbridging-the-gap-connecting-your-frontend-and-backend","BsTno2al8KO43Bs2qZ55RkYqBh_yUd6ODKPZsR-Mj8s",{"overview":1971,"chapters":2145},{"id":1972,"title":1973,"body":1974,"contentId":2129,"date":2130,"description":2131,"extension":1960,"github":1961,"meetTheInstructor":2132,"meta":2133,"navigation":131,"part":1961,"path":2134,"rawbody":2135,"robots":1961,"schemaOrg":1961,"seo":2136,"seriesSlug":1966,"sitemap":2137,"stem":2138,"subtitle":2139,"topics":2140,"__hash__":2144},"series\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api.md","Empower and Enhance Your VitePress Blog with a Laravel API",{"type":7,"value":1975,"toc":2126},[1976,1979,1982,1985,1989,1998,2001,2008,2011,2014,2097,2100,2103,2106,2116,2120],[10,1977,1978],{},"Hello! 👋",[10,1980,1981],{},"After building our VitePress blog, we are ready to make it more dynamic with a Laravel API.",[10,1983,1984],{},"In the previous series, we explored VitePress from the initial project setup to deployment on Cloudflare Pages. We built a functional, automated blog with SEO metadata, Open Graph images, and a GitHub projects page. The blog handled everything at build time, so publishing content was the only task left.",[1986,1987],"callout-read-more",{"id":1988},"43c95b33-041c-4108-ab98-0d21ef60ed7f",[10,1990,1991,1992,1997],{},"This series introduces back-end development by creating a ",[17,1993,1996],{"href":1994,"rel":1995},"https:\u002F\u002Flaravel.com",[21],"Laravel"," API that gives our blog a few interactive features.",[10,1999,2000],{},"Until now, our blog has been mostly static. Content was generated at build time, with a small amount of data loaded dynamically, and the resulting HTML files were distributed through a CDN. By adding a Laravel API, we will let readers interact with the blog through features such as post reactions and comments.",[10,2002,2003,2004,2007],{},"Although the focus is on the back end, we will also integrate the API into our VitePress blog. We will use Vue.js and ",[17,2005,1943],{"href":1941,"rel":2006},[21]," as our data-fetching framework. VitePress is a Vue.js application, so we can extend it with the components we need.",[10,2009,2010],{},"The examples are designed to be easy to follow. Unnecessary complexity and over-engineering are neither desirable nor necessary here. We will focus on simplicity, clarity, and efficiency.",[10,2012,2013],{},"Throughout the series, we will build a Laravel API and integrate it with our VitePress blog. We will cover:",[2015,2016,2017,2024,2052,2063,2069,2079,2085,2091],"ul",{},[409,2018,2019,2023],{},[2020,2021,2022],"strong",{},"Setting up the Laravel project",": Create a new Laravel project and become familiar with its structure.",[409,2025,2026,2029,2030,1614,2035,1614,2040,2045,2046,2051],{},[2020,2027,2028],{},"Improving the development workflow",": Configure ",[17,2031,2034],{"href":2032,"rel":2033},"https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fpint",[21],"Pint",[17,2036,2039],{"href":2037,"rel":2038},"https:\u002F\u002Fgithub.com\u002Frectorphp\u002Frector",[21],"Rector",[17,2041,2044],{"href":2042,"rel":2043},"https:\u002F\u002Fgithub.com\u002Flarastan\u002Flarastan",[21],"Larastan",", and ",[17,2047,2050],{"href":2048,"rel":2049},"https:\u002F\u002Fpestphp.com\u002F",[21],"Pest"," for formatting, refactoring, static analysis, and testing.",[409,2053,2054,2057,2058,796],{},[2020,2055,2056],{},"Adding social authentication",": Let users sign in with GitHub through ",[17,2059,2062],{"href":2060,"rel":2061},"https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fsocialite",[21],"Laravel Socialite",[409,2064,2065,2068],{},[2020,2066,2067],{},"Connecting the applications",": Configure Sanctum, CORS, CSRF protection, and the first requests between the VitePress frontend and the Laravel API.",[409,2070,2071,2074,2075,2078],{},[2020,2072,2073],{},"Managing authentication state",": Use ",[17,2076,1943],{"href":1941,"rel":2077},[21]," to retrieve the current user and log out with an optimistic update.",[409,2080,2081,2084],{},[2020,2082,2083],{},"Building the comment API",": Create the models, relationships, endpoints, validation, authorization, and tests for comments.",[409,2086,2087,2090],{},[2020,2088,2089],{},"Keeping the backend in sync",": Generate post metadata from VitePress and synchronize it with the Laravel database.",[409,2092,2093,2096],{},[2020,2094,2095],{},"Building the comment interface",": Fetch, create, edit, and delete comments from the VitePress frontend.",[10,2098,2099],{},"By the end of the series, you will have a blog backed by a Laravel API. Readers will be able to sign in with GitHub and leave comments, and the architecture will be ready for additional interactive features.",[10,2101,2102],{},"Testing is part of the development process and will be included at each stage, so it does not need a dedicated article.",[10,2104,2105],{},"If you have questions, feedback, or suggestions, feel free to share them in the comments. Your input helps improve the series.",[34,2107,2108],{"color":263,"icon":264},[10,2109,2110,2111,2115],{},"This series assumes prior knowledge of TypeScript, Vue.js, and Laravel. If you are unfamiliar with any of these technologies, review the ",[17,2112,2114],{"href":2113},"\u002Fseries\u002Fcreate-a-blog-with-vitepress-and-vue-js-from-scratch","Create a Blog with VitePress and Vue.js from Scratch"," first.",[42,2117,2119],{"id":2118},"chapters","Chapters",[2121,2122],"series-chapters-list",{"className":2123},[2124,2125],"mx-auto","max-w-5xl",{"title":65,"searchDepth":128,"depth":128,"links":2127},[2128],{"id":2118,"depth":128,"text":2119},"676d45dd-eb18-42ec-803e-b9d6b7f04b42","2024-11-19","Transform your VitePress blog into a dynamic platform with a Laravel API. Leverage backend API capabilities to create advanced features.","I create this series because I love \u003Cstrong>VitePress\u003C\u002Fstrong> and \u003Cstrong>Laravel\u003C\u002Fstrong>. I truly believe that combining the two results in a simple yet \u003Cstrong>powerful solution\u003C\u002Fstrong> for creating a blog. I want to empower developers to enhance their VitePress blogs with a Laravel API to create advanced features.",{},"\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api","---\ncontentId: 676d45dd-eb18-42ec-803e-b9d6b7f04b42\ntitle: Empower and Enhance Your VitePress Blog with a Laravel API\nsubtitle: Transform your VitePress blog into a dynamic platform with an API\ndescription: Transform your VitePress blog into a dynamic platform with a Laravel API. Leverage backend API capabilities to create advanced features.\ndate: 2024-11-19\ntopics:\n  - laravel\n  - vitepress\n  - api\nmeetTheInstructor: I create this series because I love \u003Cstrong>VitePress\u003C\u002Fstrong> and \u003Cstrong>Laravel\u003C\u002Fstrong>. I truly believe that combining the two results in a simple yet \u003Cstrong>powerful solution\u003C\u002Fstrong> for creating a blog. I want to empower developers to enhance their VitePress blogs with a Laravel API to create advanced features.\nseriesSlug: empower-and-dynamize-our-vitepress-blog-with-a-laravel-api\n---\n\nHello! 👋\n\nAfter building our VitePress blog, we are ready to make it more dynamic with a Laravel API.\n\nIn the previous series, we explored VitePress from the initial project setup to deployment on Cloudflare Pages. We built a functional, automated blog with SEO metadata, Open Graph images, and a GitHub projects page. The blog handled everything at build time, so publishing content was the only task left.\n\n\u003CCalloutReadMore id=\"43c95b33-041c-4108-ab98-0d21ef60ed7f\" \u002F>\n\nThis series introduces back-end development by creating a [Laravel](https:\u002F\u002Flaravel.com) API that gives our blog a few interactive features.\n\nUntil now, our blog has been mostly static. Content was generated at build time, with a small amount of data loaded dynamically, and the resulting HTML files were distributed through a CDN. By adding a Laravel API, we will let readers interact with the blog through features such as post reactions and comments.\n\nAlthough the focus is on the back end, we will also integrate the API into our VitePress blog. We will use Vue.js and [Pinia Colada](https:\u002F\u002Fpinia-colada.esm.dev\u002F) as our data-fetching framework. VitePress is a Vue.js application, so we can extend it with the components we need.\n\nThe examples are designed to be easy to follow. Unnecessary complexity and over-engineering are neither desirable nor necessary here. We will focus on simplicity, clarity, and efficiency.\n\nThroughout the series, we will build a Laravel API and integrate it with our VitePress blog. We will cover:\n\n- **Setting up the Laravel project**: Create a new Laravel project and become familiar with its structure.\n- **Improving the development workflow**: Configure [Pint](https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fpint), [Rector](https:\u002F\u002Fgithub.com\u002Frectorphp\u002Frector), [Larastan](https:\u002F\u002Fgithub.com\u002Flarastan\u002Flarastan), and [Pest](https:\u002F\u002Fpestphp.com\u002F) for formatting, refactoring, static analysis, and testing.\n- **Adding social authentication**: Let users sign in with GitHub through [Laravel Socialite](https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fsocialite).\n- **Connecting the applications**: Configure Sanctum, CORS, CSRF protection, and the first requests between the VitePress frontend and the Laravel API.\n- **Managing authentication state**: Use [Pinia Colada](https:\u002F\u002Fpinia-colada.esm.dev\u002F) to retrieve the current user and log out with an optimistic update.\n- **Building the comment API**: Create the models, relationships, endpoints, validation, authorization, and tests for comments.\n- **Keeping the backend in sync**: Generate post metadata from VitePress and synchronize it with the Laravel database.\n- **Building the comment interface**: Fetch, create, edit, and delete comments from the VitePress frontend.\n\nBy the end of the series, you will have a blog backed by a Laravel API. Readers will be able to sign in with GitHub and leave comments, and the architecture will be ready for additional interactive features.\n\nTesting is part of the development process and will be included at each stage, so it does not need a dedicated article.\n\nIf you have questions, feedback, or suggestions, feel free to share them in the comments. Your input helps improve the series.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nThis series assumes prior knowledge of TypeScript, Vue.js, and Laravel. If you are unfamiliar with any of these technologies, review the [Create a Blog with VitePress and Vue.js from Scratch](\u002Fseries\u002Fcreate-a-blog-with-vitepress-and-vue-js-from-scratch) first.\n::\n\n## Chapters\n\n::series-chapters-list\n---\nclass: mx-auto max-w-5xl\n---\n::\n",{"title":1973,"description":2131},{"loc":2134},"series\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api","Transform your VitePress blog into a dynamic platform with an API",[2141,2142,2143],"laravel","vitepress","api","JLBtX9BKfN72BkhcYisEXraNGTvZSnT5YHM05A_uemk",[2146,2151,2156,2161,2166,2171,2172,2177],{"contentId":2147,"title":2148,"description":2149,"path":2150,"part":73,"github":1961,"topics":1961},"06469e25-715e-4a92-87b9-0db6db845a50","Setting Up Your Laravel Project Structure and Essentials","A comprehensive guide to setting up your Laravel project and understanding its structure for a better development experience.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fsetting-up-your-laravel-project-structure-and-essentials",{"contentId":2152,"title":2153,"description":2154,"path":2155,"part":128,"github":1961,"topics":1961},"d566d5f4-3c4a-44e5-89cb-b3c547673ffa","Pint, Rector, Larastan, and Pest: Essentials for Success","Explore the four indispensable tools for maintaining code quality and consistency in Laravel projects: Pint, Rector, Larastan, and Pest.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fpint-larastan-rector-and-pest-essential-for-success",{"contentId":2157,"title":2158,"description":2159,"path":2160,"part":135,"github":1961,"topics":1961},"3729f419-a8b6-486c-a845-ab5ba1a33172","Effortless Social Authentication with Laravel Socialite","Add GitHub authentication to Laravel with Socialite, OAuth callbacks, database synchronization, secure sessions, and test-first development.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Feffortless-social-authentication-with-laravel-socialite",{"contentId":2162,"title":2163,"description":2164,"path":2165,"part":141,"github":1961,"topics":1961},"b07ec3b5-ca56-4d14-ae2f-8c0702218293","Building a Simple Comment System for User Engagement","Build a Laravel comment API with models, migrations, resources, policies, form requests, controllers, routes, and comprehensive tests.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbuilding-a-simple-comment-system-for-user-engagement",{"contentId":2167,"title":2168,"description":2169,"path":2170,"part":146,"github":1961,"topics":1961},"53a607df-d10e-4423-966c-500d2885e6e0","Automating Your Backend to Stay in Sync Effortlessly","Generate frontend metadata with VitePress, synchronize posts with Laravel, and keep the backend database aligned automatically.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fautomating-your-backend-to-stay-in-sync-effortlessly",{"contentId":1957,"title":5,"description":1959,"path":1963,"part":152,"github":1961,"topics":1961},{"contentId":2173,"title":2174,"description":2175,"path":2176,"part":158,"github":1961,"topics":1961},"d507f8af-7c76-4660-859e-23af11c0728e","Streamlining User Authentication from Frontend to Backend","Connect frontend authentication to Laravel with a current-user query, GitHub logout flow, Pinia Colada caching, and optimistic state updates.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fstreamlining-user-authentication-from-frontend-to-backend",{"contentId":2178,"title":2179,"description":2180,"path":2181,"part":163,"github":1961,"topics":1961},"1b2a6cc0-c10f-421a-9344-60cb1583a136","Simplifying Comment Querying and Editing with Pinia Colada","Build the VitePress comment interface with Pinia Colada queries, mutations, optimistic updates, reusable Vue components, and permissions.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fsimplifying-comment-querying-and-editing-with-pinia-colada",1795016693801]