[{"data":1,"prerenderedAt":3489},["ShallowReactive",2],{"series-\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fstreamlining-user-authentication-from-frontend-to-backend":3,"series-context-\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api":3277},{"id":4,"title":5,"body":6,"contentId":3264,"date":3265,"description":3266,"extension":3267,"github":3268,"meetTheInstructor":3268,"meta":3269,"navigation":86,"part":112,"path":3270,"rawbody":3271,"robots":3268,"schemaOrg":3268,"seo":3272,"seriesSlug":3273,"sitemap":3274,"stem":3275,"subtitle":3268,"topics":3268,"__hash__":3276},"series\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fstreamlining-user-authentication-from-frontend-to-backend.md","Streamlining User Authentication from Frontend to Backend",{"type":7,"value":8,"toc":3253},"minimark",[9,13,16,27,32,35,52,55,60,63,250,253,256,341,360,367,425,428,432,435,524,527,529,636,643,651,656,685,696,711,739,742,746,749,752,755,758,881,894,909,912,915,918,921,930,933,956,959,1067,1070,1077,1088,1091,1117,1128,1132,1142,1573,1577,1584,1880,1891,1895,1898,1904,1928,1934,1999,2010,2018,2021,2150,2153,2213,2216,2258,2264,2267,2275,2278,2560,2575,2581,2791,2794,2961,2967,3021,3039,3044,3128,3133,3218,3225,3228,3239,3243,3246,3249],[10,11,12],"p",{},"Now that the frontend can reach the Laravel API, we can use that connection to manage authentication throughout the application.",[10,14,15],{},"So far, we have tested requests in isolation. In this article, we will fetch the current user when the application starts, display the appropriate login or logout action, and implement logout with an optimistic update. The interface will update immediately while the API request runs, then recover if the request fails.",[10,17,18,19,26],{},"To manage this cleanly, we will combine Pinia with Pinia Colada, a data-fetching library built on top of Pinia and created by ",[20,21,25],"a",{"href":22,"rel":23},"https:\u002F\u002Fgithub.com\u002Fposva",[24],"nofollow","Eduardo",", the creator of Pinia. It will give us shared cached state, request status, and the mutation hooks we need for optimistic updates.",[28,29,31],"h2",{"id":30},"setting-up-the-api","Setting up the API",[10,33,34],{},"To support the frontend, we need two new routes in the Laravel application:",[36,37,38,46],"ol",{},[39,40,41,45],"li",{},[42,43,44],"code",{},"GET \u002Fapi\u002Fuser",": Returns the authenticated user. The frontend calls it when the application starts to adapt the interface.",[39,47,48,51],{},[42,49,50],{},"POST \u002Flogout",": Logs out the user and invalidates the current session when the frontend's logout button is clicked.",[10,53,54],{},"For each route, we will write tests, create a controller method, and register the route. This follows the same process as the previous articles.",[56,57,59],"h3",{"id":58},"returning-the-user","Returning the user",[10,61,62],{},"Let's start with the first route. We will create a test to check if the user is authenticated and if the user data is returned correctly.",[64,65,71],"pre",{"className":66,"code":67,"filename":68,"language":69,"meta":70,"style":70},"language-php shiki shiki-themes github-light github-light github-dark","\u003C?php\n\ndeclare(strict_types=1);\n\nuse Illuminate\\Testing\\Fluent\\AssertableJson;\n\nit('requires authentification', function () {\n    $this->getJson(route('user.show'))\n        ->assertUnauthorized();\n});\n\nit('returns the authenticated user', function () {\n    $user = App\\Models\\User::factory()->create();\n\n    $response = $this->actingAs($user)\n        ->getJson(route('user.show'));\n\n    $response\n        ->assertOk()\n        ->assertJson(\n            fn (AssertableJson $json) => $json\n                ->has(\n                    'data',\n                    fn (AssertableJson $json) => $json\n                        ->where('name', $user->name)\n                        ->where('username', $user->username)\n                        ->where('avatar', $user->avatar)\n                )\n        );\n});\n","tests\u002FHttp\u002FAuth\u002FAuthenticationSessionTest.php","php","",[42,72,73,81,88,94,99,105,110,116,122,128,134,139,145,151,156,162,168,173,179,185,191,197,203,209,215,221,227,233,239,245],{"__ignoreMap":70},[74,75,78],"span",{"class":76,"line":77},"line",1,[74,79,80],{},"\u003C?php\n",[74,82,84],{"class":76,"line":83},2,[74,85,87],{"emptyLinePlaceholder":86},true,"\n",[74,89,91],{"class":76,"line":90},3,[74,92,93],{},"declare(strict_types=1);\n",[74,95,97],{"class":76,"line":96},4,[74,98,87],{"emptyLinePlaceholder":86},[74,100,102],{"class":76,"line":101},5,[74,103,104],{},"use Illuminate\\Testing\\Fluent\\AssertableJson;\n",[74,106,108],{"class":76,"line":107},6,[74,109,87],{"emptyLinePlaceholder":86},[74,111,113],{"class":76,"line":112},7,[74,114,115],{},"it('requires authentification', function () {\n",[74,117,119],{"class":76,"line":118},8,[74,120,121],{},"    $this->getJson(route('user.show'))\n",[74,123,125],{"class":76,"line":124},9,[74,126,127],{},"        ->assertUnauthorized();\n",[74,129,131],{"class":76,"line":130},10,[74,132,133],{},"});\n",[74,135,137],{"class":76,"line":136},11,[74,138,87],{"emptyLinePlaceholder":86},[74,140,142],{"class":76,"line":141},12,[74,143,144],{},"it('returns the authenticated user', function () {\n",[74,146,148],{"class":76,"line":147},13,[74,149,150],{},"    $user = App\\Models\\User::factory()->create();\n",[74,152,154],{"class":76,"line":153},14,[74,155,87],{"emptyLinePlaceholder":86},[74,157,159],{"class":76,"line":158},15,[74,160,161],{},"    $response = $this->actingAs($user)\n",[74,163,165],{"class":76,"line":164},16,[74,166,167],{},"        ->getJson(route('user.show'));\n",[74,169,171],{"class":76,"line":170},17,[74,172,87],{"emptyLinePlaceholder":86},[74,174,176],{"class":76,"line":175},18,[74,177,178],{},"    $response\n",[74,180,182],{"class":76,"line":181},19,[74,183,184],{},"        ->assertOk()\n",[74,186,188],{"class":76,"line":187},20,[74,189,190],{},"        ->assertJson(\n",[74,192,194],{"class":76,"line":193},21,[74,195,196],{},"            fn (AssertableJson $json) => $json\n",[74,198,200],{"class":76,"line":199},22,[74,201,202],{},"                ->has(\n",[74,204,206],{"class":76,"line":205},23,[74,207,208],{},"                    'data',\n",[74,210,212],{"class":76,"line":211},24,[74,213,214],{},"                    fn (AssertableJson $json) => $json\n",[74,216,218],{"class":76,"line":217},25,[74,219,220],{},"                        ->where('name', $user->name)\n",[74,222,224],{"class":76,"line":223},26,[74,225,226],{},"                        ->where('username', $user->username)\n",[74,228,230],{"class":76,"line":229},27,[74,231,232],{},"                        ->where('avatar', $user->avatar)\n",[74,234,236],{"class":76,"line":235},28,[74,237,238],{},"                )\n",[74,240,242],{"class":76,"line":241},29,[74,243,244],{},"        );\n",[74,246,248],{"class":76,"line":247},30,[74,249,133],{},[10,251,252],{},"These tests are similar to the comment tests. The first verifies authentication, and the second checks the user data in the JSON response.",[10,254,255],{},"Now, let's create the controller:",[64,257,260],{"className":66,"code":258,"filename":259,"language":69,"meta":70,"style":70},"\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Controllers\\Api;\n\nuse App\\Http\\Resources\\UserResource;\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Http\\Resources\\Json\\JsonResource;\n\nfinal class UserController\n{\n    public function show(Request $request): JsonResource\n    {\n        return UserResource::make($request->user());\n    }\n}\n","app\u002FHttp\u002FControllers\u002FAuth\u002FAuthenticatedSessionController.php",[42,261,262,266,270,274,278,283,287,292,297,302,306,311,316,321,326,331,336],{"__ignoreMap":70},[74,263,264],{"class":76,"line":77},[74,265,80],{},[74,267,268],{"class":76,"line":83},[74,269,87],{"emptyLinePlaceholder":86},[74,271,272],{"class":76,"line":90},[74,273,93],{},[74,275,276],{"class":76,"line":96},[74,277,87],{"emptyLinePlaceholder":86},[74,279,280],{"class":76,"line":101},[74,281,282],{},"namespace App\\Http\\Controllers\\Api;\n",[74,284,285],{"class":76,"line":107},[74,286,87],{"emptyLinePlaceholder":86},[74,288,289],{"class":76,"line":112},[74,290,291],{},"use App\\Http\\Resources\\UserResource;\n",[74,293,294],{"class":76,"line":118},[74,295,296],{},"use Illuminate\\Http\\Request;\n",[74,298,299],{"class":76,"line":124},[74,300,301],{},"use Illuminate\\Http\\Resources\\Json\\JsonResource;\n",[74,303,304],{"class":76,"line":130},[74,305,87],{"emptyLinePlaceholder":86},[74,307,308],{"class":76,"line":136},[74,309,310],{},"final class UserController\n",[74,312,313],{"class":76,"line":141},[74,314,315],{},"{\n",[74,317,318],{"class":76,"line":147},[74,319,320],{},"    public function show(Request $request): JsonResource\n",[74,322,323],{"class":76,"line":153},[74,324,325],{},"    {\n",[74,327,328],{"class":76,"line":158},[74,329,330],{},"        return UserResource::make($request->user());\n",[74,332,333],{"class":76,"line":164},[74,334,335],{},"    }\n",[74,337,338],{"class":76,"line":170},[74,339,340],{},"}\n",[10,342,343,344,347,348,351,352,355,356,359],{},"This controller uses ",[42,345,346],{},"UserResource"," to transform the authenticated user into a JSON response. We created that resource in the comment-system article; it exposes the ",[42,349,350],{},"name",", ",[42,353,354],{},"username",", and ",[42,357,358],{},"avatar"," fields.",[10,361,362,363,366],{},"Finally, we need to register the route in the ",[42,364,365],{},"routes\u002Fapi.php"," file:",[64,368,370],{"className":66,"code":369,"filename":365,"language":69,"meta":70,"style":70},"\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Http\\Controllers\\Api\\UserController;\n\nRoute::middleware('auth:sanctum')->group(function () {\n    Route::get('\u002Fuser', [UserController::class, 'show'])\n        ->name('user.show');\n\n    \u002F\u002F ...\n});\n",[42,371,372,376,380,384,388,393,397,402,407,412,416,421],{"__ignoreMap":70},[74,373,374],{"class":76,"line":77},[74,375,80],{},[74,377,378],{"class":76,"line":83},[74,379,87],{"emptyLinePlaceholder":86},[74,381,382],{"class":76,"line":90},[74,383,93],{},[74,385,386],{"class":76,"line":96},[74,387,87],{"emptyLinePlaceholder":86},[74,389,390],{"class":76,"line":101},[74,391,392],{},"use App\\Http\\Controllers\\Api\\UserController;\n",[74,394,395],{"class":76,"line":107},[74,396,87],{"emptyLinePlaceholder":86},[74,398,399],{"class":76,"line":112},[74,400,401],{},"Route::middleware('auth:sanctum')->group(function () {\n",[74,403,404],{"class":76,"line":118},[74,405,406],{},"    Route::get('\u002Fuser', [UserController::class, 'show'])\n",[74,408,409],{"class":76,"line":124},[74,410,411],{},"        ->name('user.show');\n",[74,413,414],{"class":76,"line":130},[74,415,87],{"emptyLinePlaceholder":86},[74,417,418],{"class":76,"line":136},[74,419,420],{},"    \u002F\u002F ...\n",[74,422,423],{"class":76,"line":141},[74,424,133],{},[10,426,427],{},"That is enough to retrieve the current user.",[56,429,431],{"id":430},"logging-out-the-user","Logging out the user",[10,433,434],{},"Let's get started with the tests:",[64,436,438],{"className":66,"code":437,"filename":68,"language":69,"meta":70,"style":70},"\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\User;\n\nit('requires authentification', function () {\n    $this->postJson(route('logout'))\n        ->assertUnauthorized();\n});\n\nit('destroys the session', function () {\n    $response = $this->actingAs(User::factory()->create())\n        ->post(route('logout'))\n        ->assertNoContent();\n\n    $this->assertGuest('web');\n    $response->assertNoContent();\n});\n",[42,439,440,444,448,452,456,461,465,469,474,478,482,486,491,496,501,506,510,515,520],{"__ignoreMap":70},[74,441,442],{"class":76,"line":77},[74,443,80],{},[74,445,446],{"class":76,"line":83},[74,447,87],{"emptyLinePlaceholder":86},[74,449,450],{"class":76,"line":90},[74,451,93],{},[74,453,454],{"class":76,"line":96},[74,455,87],{"emptyLinePlaceholder":86},[74,457,458],{"class":76,"line":101},[74,459,460],{},"use App\\Models\\User;\n",[74,462,463],{"class":76,"line":107},[74,464,87],{"emptyLinePlaceholder":86},[74,466,467],{"class":76,"line":112},[74,468,115],{},[74,470,471],{"class":76,"line":118},[74,472,473],{},"    $this->postJson(route('logout'))\n",[74,475,476],{"class":76,"line":124},[74,477,127],{},[74,479,480],{"class":76,"line":130},[74,481,133],{},[74,483,484],{"class":76,"line":136},[74,485,87],{"emptyLinePlaceholder":86},[74,487,488],{"class":76,"line":141},[74,489,490],{},"it('destroys the session', function () {\n",[74,492,493],{"class":76,"line":147},[74,494,495],{},"    $response = $this->actingAs(User::factory()->create())\n",[74,497,498],{"class":76,"line":153},[74,499,500],{},"        ->post(route('logout'))\n",[74,502,503],{"class":76,"line":158},[74,504,505],{},"        ->assertNoContent();\n",[74,507,508],{"class":76,"line":164},[74,509,87],{"emptyLinePlaceholder":86},[74,511,512],{"class":76,"line":170},[74,513,514],{},"    $this->assertGuest('web');\n",[74,516,517],{"class":76,"line":175},[74,518,519],{},"    $response->assertNoContent();\n",[74,521,522],{"class":76,"line":181},[74,523,133],{},[10,525,526],{},"These tests follow the same patterns as the previous ones.",[10,528,255],{},[64,530,533],{"className":66,"code":531,"filename":532,"language":69,"meta":70,"style":70},"\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Controllers\\Auth;\n\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Http\\Response;\nuse Illuminate\\Support\\Facades\\Auth;\n\nfinal class AuthenticatedSessionController\n{\n    public function destroy(Request $request): Response\n    {\n        Auth::guard('web')->logout();\n\n        $request->session()->invalidate();\n\n        $request->session()->regenerateToken();\n\n        return response()->noContent();\n    }\n}\n","app\u002FHttp\u002FControllers\u002FAuth\u002FAuthenticationSessionController.php",[42,534,535,539,543,547,551,556,560,564,569,574,578,583,587,592,596,601,605,610,614,619,623,628,632],{"__ignoreMap":70},[74,536,537],{"class":76,"line":77},[74,538,80],{},[74,540,541],{"class":76,"line":83},[74,542,87],{"emptyLinePlaceholder":86},[74,544,545],{"class":76,"line":90},[74,546,93],{},[74,548,549],{"class":76,"line":96},[74,550,87],{"emptyLinePlaceholder":86},[74,552,553],{"class":76,"line":101},[74,554,555],{},"namespace App\\Http\\Controllers\\Auth;\n",[74,557,558],{"class":76,"line":107},[74,559,87],{"emptyLinePlaceholder":86},[74,561,562],{"class":76,"line":112},[74,563,296],{},[74,565,566],{"class":76,"line":118},[74,567,568],{},"use Illuminate\\Http\\Response;\n",[74,570,571],{"class":76,"line":124},[74,572,573],{},"use Illuminate\\Support\\Facades\\Auth;\n",[74,575,576],{"class":76,"line":130},[74,577,87],{"emptyLinePlaceholder":86},[74,579,580],{"class":76,"line":136},[74,581,582],{},"final class AuthenticatedSessionController\n",[74,584,585],{"class":76,"line":141},[74,586,315],{},[74,588,589],{"class":76,"line":147},[74,590,591],{},"    public function destroy(Request $request): Response\n",[74,593,594],{"class":76,"line":153},[74,595,325],{},[74,597,598],{"class":76,"line":158},[74,599,600],{},"        Auth::guard('web')->logout();\n",[74,602,603],{"class":76,"line":164},[74,604,87],{"emptyLinePlaceholder":86},[74,606,607],{"class":76,"line":170},[74,608,609],{},"        $request->session()->invalidate();\n",[74,611,612],{"class":76,"line":175},[74,613,87],{"emptyLinePlaceholder":86},[74,615,616],{"class":76,"line":181},[74,617,618],{},"        $request->session()->regenerateToken();\n",[74,620,621],{"class":76,"line":187},[74,622,87],{"emptyLinePlaceholder":86},[74,624,625],{"class":76,"line":193},[74,626,627],{},"        return response()->noContent();\n",[74,629,630],{"class":76,"line":199},[74,631,335],{},[74,633,634],{"class":76,"line":205},[74,635,340],{},[10,637,638,639,642],{},"The controller uses Laravel's ",[42,640,641],{},"Auth"," facade to log out the user. It then invalidates the session and regenerates the CSRF token. These steps help prevent session-fixation attacks.",[644,645,648],"callout",{"color":646,"icon":647},"info","i-ph-info-duotone",[10,649,650],{},"The controller returns an empty response because the frontend does not need a response body for logout.",[10,652,362,653,366],{},[42,654,655],{},"routes\u002Fweb.php",[64,657,659],{"className":66,"code":658,"filename":655,"language":69,"meta":70,"style":70},"use App\\Http\\Controllers\\Auth\\AuthenticatedSessionController;\n\nRoute::post('logout', [AuthenticatedSessionController::class, 'destroy'])\n    ->middleware('auth:sanctum')\n    ->name('logout');\n",[42,660,661,666,670,675,680],{"__ignoreMap":70},[74,662,663],{"class":76,"line":77},[74,664,665],{},"use App\\Http\\Controllers\\Auth\\AuthenticatedSessionController;\n",[74,667,668],{"class":76,"line":83},[74,669,87],{"emptyLinePlaceholder":86},[74,671,672],{"class":76,"line":90},[74,673,674],{},"Route::post('logout', [AuthenticatedSessionController::class, 'destroy'])\n",[74,676,677],{"class":76,"line":96},[74,678,679],{},"    ->middleware('auth:sanctum')\n",[74,681,682],{"class":76,"line":101},[74,683,684],{},"    ->name('logout');\n",[10,686,687,688,691,692,695],{},"This route uses the ",[42,689,690],{},"auth:sanctum"," middleware even though it is defined in ",[42,693,694],{},"web.php",". It does not return JSON and does not need to be versioned with the other API routes, so keeping it as a web route is reasonable.",[10,697,698,699,702,703,706,707,710],{},"In the ",[42,700,701],{},"config\u002Fcors.php"," config file, we also need to add the ",[42,704,705],{},"logout"," route to the ",[42,708,709],{},"paths"," array:",[64,712,714],{"className":66,"code":713,"filename":701,"language":69,"meta":70,"style":70},"return [\n    'paths' => ['api\u002F*', 'logout'],\n\n    \u002F\u002F ...\n];\n",[42,715,716,721,726,730,734],{"__ignoreMap":70},[74,717,718],{"class":76,"line":77},[74,719,720],{},"return [\n",[74,722,723],{"class":76,"line":83},[74,724,725],{},"    'paths' => ['api\u002F*', 'logout'],\n",[74,727,728],{"class":76,"line":90},[74,729,87],{"emptyLinePlaceholder":86},[74,731,732],{"class":76,"line":96},[74,733,420],{},[74,735,736],{"class":76,"line":101},[74,737,738],{},"];\n",[10,740,741],{},"This allows the frontend to call the route from a different origin. Without it, the browser would block the request because of CORS.",[28,743,745],{"id":744},"preparing-the-frontend","Preparing the frontend",[10,747,748],{},"The backend is ready, so we can move to the frontend.",[10,750,751],{},"We will retrieve the user when the application starts so the interface can react to the authentication state. Several components need this information. The header currently displays a login button; we will add a logout button for authenticated users and hide the login button in that case.",[10,753,754],{},"The footer may also need a login or logout link, and the comment system will need the same state to decide whether to display a login button or a comment form.",[10,756,757],{},"The simplest solution would be a shared composable:",[64,759,764],{"className":760,"code":761,"filename":762,"language":763,"meta":70,"style":70},"language-js shiki shiki-themes github-light github-light github-dark","const user = ref(null)\n\nexport function useUser() {\n  async function fetch() {\n    \u002F\u002F Simulate fetching user data from the backend\n    user.value = await fetchUserData()\n  }\n\n  return {\n    user,\n    fetch,\n  }\n}\n","Example","js",[42,765,766,793,797,811,823,829,846,851,855,863,868,873,877],{"__ignoreMap":70},[74,767,768,772,776,779,783,787,790],{"class":76,"line":77},[74,769,771],{"class":770},"s8jYJ","const",[74,773,775],{"class":774},"sBjJW"," user",[74,777,778],{"class":770}," =",[74,780,782],{"class":781},"snPdu"," ref",[74,784,786],{"class":785},"sxrX7","(",[74,788,789],{"class":774},"null",[74,791,792],{"class":785},")\n",[74,794,795],{"class":76,"line":83},[74,796,87],{"emptyLinePlaceholder":86},[74,798,799,802,805,808],{"class":76,"line":90},[74,800,801],{"class":770},"export",[74,803,804],{"class":770}," function",[74,806,807],{"class":781}," useUser",[74,809,810],{"class":785},"() {\n",[74,812,813,816,818,821],{"class":76,"line":96},[74,814,815],{"class":770},"  async",[74,817,804],{"class":770},[74,819,820],{"class":781}," fetch",[74,822,810],{"class":785},[74,824,825],{"class":76,"line":101},[74,826,828],{"class":827},"sCsY4","    \u002F\u002F Simulate fetching user data from the backend\n",[74,830,831,834,837,840,843],{"class":76,"line":107},[74,832,833],{"class":785},"    user.value ",[74,835,836],{"class":770},"=",[74,838,839],{"class":770}," await",[74,841,842],{"class":781}," fetchUserData",[74,844,845],{"class":785},"()\n",[74,847,848],{"class":76,"line":112},[74,849,850],{"class":785},"  }\n",[74,852,853],{"class":76,"line":118},[74,854,87],{"emptyLinePlaceholder":86},[74,856,857,860],{"class":76,"line":124},[74,858,859],{"class":770},"  return",[74,861,862],{"class":785}," {\n",[74,864,865],{"class":76,"line":130},[74,866,867],{"class":785},"    user,\n",[74,869,870],{"class":76,"line":136},[74,871,872],{"class":785},"    fetch,\n",[74,874,875],{"class":76,"line":141},[74,876,850],{"class":785},[74,878,879],{"class":76,"line":147},[74,880,340],{"class":785},[644,882,883],{"color":646,"icon":647},[10,884,885,886,893],{},"We could also use the ",[20,887,890],{"href":888,"rel":889},"https:\u002F\u002Fvueuse.org\u002Fshared\u002FcreateSharedComposable\u002F#createsharedcomposable",[24],[42,891,892],{},"createSharedComposable"," from Vueuse to avoid having global state while keeping the same instance of the composable in all components.",[10,895,896,897,900,901,904,905,908],{},"We would then call ",[42,898,899],{},"fetch"," in the ",[42,902,903],{},"onMounted"," hook of the main component, ",[42,906,907],{},"Layout.vue"," in our case.",[10,910,911],{},"This solution works for a while, but it quickly becomes difficult to maintain. One component performs the fetch while many others consume the result. That may be manageable for one data type, but it becomes messy as the application grows.",[10,913,914],{},"We would also need boilerplate to manage mutation state. Logging out, creating a comment, and deleting a comment all need loading and error states. Repeating this code would either make components noisy or push us toward a collection of custom utilities.",[10,916,917],{},"We may also want optimistic updates. Logout is a good example: remove the user from state immediately, call the API, and restore the user if the request fails. Implementing that reliably and generically is not trivial.",[10,919,920],{},"To avoid this boilerplate, we will combine Pinia with Pinia Colada.",[922,923,924,927],"ul",{},[39,925,926],{},"Pinia is Vue's state-management library. A store centralizes state, getters, and actions, while the UI reacts to changes in that state.",[39,928,929],{},"Pinia Colada is a data-fetching library built on top of Pinia. It manages requests and cache state, and it provides the hooks we need for optimistic updates.",[10,931,932],{},"Install Pinia and Pinia Colada in the Garabit project:",[64,934,939],{"className":935,"code":936,"filename":937,"language":938,"meta":70,"style":70},"language-bash shiki shiki-themes github-light github-light github-dark","pnpm install pinia @pinia\u002Fcolada\n","terminal","bash",[42,940,941],{"__ignoreMap":70},[74,942,943,946,950,953],{"class":76,"line":77},[74,944,945],{"class":781},"pnpm",[74,947,949],{"class":948},"sIIMD"," install",[74,951,952],{"class":948}," pinia",[74,954,955],{"class":948}," @pinia\u002Fcolada\n",[10,957,958],{},"Then, we need to register them in our Vue application:",[64,960,965],{"className":961,"code":962,"filename":963,"language":964,"meta":70,"style":70},"language-ts shiki shiki-themes github-light github-light github-dark","import { PiniaColada } from '@pinia\u002Fcolada'\nimport { createPinia } from 'pinia'\n\nexport default {\n  Layout,\n  enhanceApp({ app }) {\n    app.use(createPinia())\n    app.use(PiniaColada)\n  },\n} satisfies Theme\n",".vitepress\u002Ftheme\u002Findex.ts","ts",[42,966,967,981,993,997,1006,1011,1026,1042,1051,1056],{"__ignoreMap":70},[74,968,969,972,975,978],{"class":76,"line":77},[74,970,971],{"class":770},"import",[74,973,974],{"class":785}," { PiniaColada } ",[74,976,977],{"class":770},"from",[74,979,980],{"class":948}," '@pinia\u002Fcolada'\n",[74,982,983,985,988,990],{"class":76,"line":83},[74,984,971],{"class":770},[74,986,987],{"class":785}," { createPinia } ",[74,989,977],{"class":770},[74,991,992],{"class":948}," 'pinia'\n",[74,994,995],{"class":76,"line":90},[74,996,87],{"emptyLinePlaceholder":86},[74,998,999,1001,1004],{"class":76,"line":96},[74,1000,801],{"class":770},[74,1002,1003],{"class":770}," default",[74,1005,862],{"class":785},[74,1007,1008],{"class":76,"line":101},[74,1009,1010],{"class":785},"  Layout,\n",[74,1012,1013,1016,1019,1023],{"class":76,"line":107},[74,1014,1015],{"class":781},"  enhanceApp",[74,1017,1018],{"class":785},"({ ",[74,1020,1022],{"class":1021},"sP4rz","app",[74,1024,1025],{"class":785}," }) {\n",[74,1027,1028,1031,1034,1036,1039],{"class":76,"line":112},[74,1029,1030],{"class":785},"    app.",[74,1032,1033],{"class":781},"use",[74,1035,786],{"class":785},[74,1037,1038],{"class":781},"createPinia",[74,1040,1041],{"class":785},"())\n",[74,1043,1044,1046,1048],{"class":76,"line":118},[74,1045,1030],{"class":785},[74,1047,1033],{"class":781},[74,1049,1050],{"class":785},"(PiniaColada)\n",[74,1052,1053],{"class":76,"line":124},[74,1054,1055],{"class":785},"  },\n",[74,1057,1058,1061,1064],{"class":76,"line":130},[74,1059,1060],{"class":785},"} ",[74,1062,1063],{"class":770},"satisfies",[74,1065,1066],{"class":781}," Theme\n",[10,1068,1069],{},"Both packages are Vue plugins that add application-level functionality.",[10,1071,1072,1073,1076],{},"Remove the temporary request code from ",[42,1074,1075],{},".vitepress\u002Ftheme\u002FLayout.vue","; the shared API client will replace it.",[10,1078,1079,1080,1083,1084,1087],{},"Before writing the feature code, let us define the structure. In ",[42,1081,1082],{},"common\u002Futils\u002Fapi.ts",", we will create a custom ",[42,1085,1086],{},"ofetch"," instance so every request uses the same host, headers, credentials, and CSRF handling. This is the code we introduced in the previous article.",[10,1089,1090],{},"Each feature will contain two folders and one API file:",[36,1092,1093,1102,1111],{},[39,1094,1095,1098,1099,1101],{},[42,1096,1097],{},"queries",": Contains requests that retrieve data. ",[42,1100,44],{}," is a query.",[39,1103,1104,1107,1108,1110],{},[42,1105,1106],{},"mutations",": Contains requests that modify data. ",[42,1109,50],{}," is a mutation.",[39,1112,1113,1116],{},[42,1114,1115],{},"api.ts",": Contains the low-level functions that make the requests. This file stays independent of the state-management library, which keeps the API layer easy to read and test.",[10,1118,1119,1120,1123,1124,1127],{},"These folders and the API file will exist for each feature. Today we will create the ",[42,1121,1122],{},"user"," feature. The next article will add a ",[42,1125,1126],{},"comments"," feature. This separation keeps related code together and makes it easier to find.",[28,1129,1131],{"id":1130},"extending-ofetch","Extending ofetch",[10,1133,1134,1135,1137,1138,1141],{},"Create the custom ",[42,1136,1086],{}," instance in ",[42,1139,1140],{},".vitepress\u002Ftheme\u002Fcommon\u002Futils\u002Fapi.ts",":",[64,1143,1145],{"className":961,"code":1144,"filename":1140,"language":964,"meta":70,"style":70},"import { ofetch } from 'ofetch'\n\nexport const api = ofetch.create({\n  baseURL: import.meta.env.VITE_API_URL,\n  headers: {\n    Accept: 'application\u002Fjson',\n  },\n  credentials: 'include',\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(\n      'X-Xsrf-Token',\n      decodeURIComponent(getCookie('XSRF-TOKEN') || ''),\n    )\n  },\n})\n\nfunction getCookie(name: string) {\n  const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`))\n  return match ? match[2] : null\n}\n",[42,1146,1147,1159,1163,1184,1206,1211,1221,1225,1235,1260,1285,1289,1319,1324,1328,1332,1351,1355,1368,1384,1401,1410,1415,1419,1423,1434,1441,1466,1471,1475,1480,1485,1505,1543,1568],{"__ignoreMap":70},[74,1148,1149,1151,1154,1156],{"class":76,"line":77},[74,1150,971],{"class":770},[74,1152,1153],{"class":785}," { ofetch } ",[74,1155,977],{"class":770},[74,1157,1158],{"class":948}," 'ofetch'\n",[74,1160,1161],{"class":76,"line":83},[74,1162,87],{"emptyLinePlaceholder":86},[74,1164,1165,1167,1170,1173,1175,1178,1181],{"class":76,"line":90},[74,1166,801],{"class":770},[74,1168,1169],{"class":770}," const",[74,1171,1172],{"class":774}," api",[74,1174,778],{"class":770},[74,1176,1177],{"class":785}," ofetch.",[74,1179,1180],{"class":781},"create",[74,1182,1183],{"class":785},"({\n",[74,1185,1186,1189,1191,1194,1197,1200,1203],{"class":76,"line":96},[74,1187,1188],{"class":785},"  baseURL: ",[74,1190,971],{"class":770},[74,1192,1193],{"class":785},".",[74,1195,1196],{"class":774},"meta",[74,1198,1199],{"class":785},".env.",[74,1201,1202],{"class":774},"VITE_API_URL",[74,1204,1205],{"class":785},",\n",[74,1207,1208],{"class":76,"line":101},[74,1209,1210],{"class":785},"  headers: {\n",[74,1212,1213,1216,1219],{"class":76,"line":107},[74,1214,1215],{"class":785},"    Accept: ",[74,1217,1218],{"class":948},"'application\u002Fjson'",[74,1220,1205],{"class":785},[74,1222,1223],{"class":76,"line":112},[74,1224,1055],{"class":785},[74,1226,1227,1230,1233],{"class":76,"line":118},[74,1228,1229],{"class":785},"  credentials: ",[74,1231,1232],{"class":948},"'include'",[74,1234,1205],{"class":785},[74,1236,1237,1240,1243,1246,1249,1252,1255,1258],{"class":76,"line":124},[74,1238,1239],{"class":781},"  onRequest",[74,1241,1242],{"class":785},": ",[74,1244,1245],{"class":770},"async",[74,1247,1248],{"class":785}," ({ ",[74,1250,1251],{"class":1021},"options",[74,1253,1254],{"class":785}," }) ",[74,1256,1257],{"class":770},"=>",[74,1259,862],{"class":785},[74,1261,1262,1265,1268,1270,1273,1276,1279,1282],{"class":76,"line":130},[74,1263,1264],{"class":770},"    const",[74,1266,1267],{"class":774}," method",[74,1269,778],{"class":770},[74,1271,1272],{"class":785}," options.method?.",[74,1274,1275],{"class":781},"toUpperCase",[74,1277,1278],{"class":785},"() ",[74,1280,1281],{"class":770},"||",[74,1283,1284],{"class":948}," 'GET'\n",[74,1286,1287],{"class":76,"line":136},[74,1288,87],{"emptyLinePlaceholder":86},[74,1290,1291,1294,1297,1300,1302,1305,1307,1310,1313,1316],{"class":76,"line":141},[74,1292,1293],{"class":770},"    if",[74,1295,1296],{"class":785}," ([",[74,1298,1299],{"class":948},"'GET'",[74,1301,351],{"class":785},[74,1303,1304],{"class":948},"'HEAD'",[74,1306,351],{"class":785},[74,1308,1309],{"class":948},"'OPTIONS'",[74,1311,1312],{"class":785},"].",[74,1314,1315],{"class":781},"includes",[74,1317,1318],{"class":785},"(method)) {\n",[74,1320,1321],{"class":76,"line":147},[74,1322,1323],{"class":770},"      return\n",[74,1325,1326],{"class":76,"line":153},[74,1327,335],{"class":785},[74,1329,1330],{"class":76,"line":158},[74,1331,87],{"emptyLinePlaceholder":86},[74,1333,1334,1336,1339,1341,1344,1346,1349],{"class":76,"line":164},[74,1335,1264],{"class":770},[74,1337,1338],{"class":774}," xsrfToken",[74,1340,778],{"class":770},[74,1342,1343],{"class":781}," getCookie",[74,1345,786],{"class":785},[74,1347,1348],{"class":948},"'XSRF-TOKEN'",[74,1350,792],{"class":785},[74,1352,1353],{"class":76,"line":170},[74,1354,87],{"emptyLinePlaceholder":86},[74,1356,1357,1359,1362,1365],{"class":76,"line":175},[74,1358,1293],{"class":770},[74,1360,1361],{"class":785}," (",[74,1363,1364],{"class":770},"!",[74,1366,1367],{"class":785},"xsrfToken) {\n",[74,1369,1370,1373,1376,1378,1381],{"class":76,"line":181},[74,1371,1372],{"class":770},"      await",[74,1374,1375],{"class":781}," ofetch",[74,1377,786],{"class":785},[74,1379,1380],{"class":948},"'\u002Fsanctum\u002Fcsrf-cookie'",[74,1382,1383],{"class":785},", {\n",[74,1385,1386,1389,1391,1393,1395,1397,1399],{"class":76,"line":187},[74,1387,1388],{"class":785},"        baseURL: ",[74,1390,971],{"class":770},[74,1392,1193],{"class":785},[74,1394,1196],{"class":774},[74,1396,1199],{"class":785},[74,1398,1202],{"class":774},[74,1400,1205],{"class":785},[74,1402,1403,1406,1408],{"class":76,"line":193},[74,1404,1405],{"class":785},"        credentials: ",[74,1407,1232],{"class":948},[74,1409,1205],{"class":785},[74,1411,1412],{"class":76,"line":199},[74,1413,1414],{"class":785},"      })\n",[74,1416,1417],{"class":76,"line":205},[74,1418,335],{"class":785},[74,1420,1421],{"class":76,"line":211},[74,1422,87],{"emptyLinePlaceholder":86},[74,1424,1425,1428,1431],{"class":76,"line":217},[74,1426,1427],{"class":785},"    options.headers.",[74,1429,1430],{"class":781},"set",[74,1432,1433],{"class":785},"(\n",[74,1435,1436,1439],{"class":76,"line":223},[74,1437,1438],{"class":948},"      'X-Xsrf-Token'",[74,1440,1205],{"class":785},[74,1442,1443,1446,1448,1451,1453,1455,1458,1460,1463],{"class":76,"line":229},[74,1444,1445],{"class":781},"      decodeURIComponent",[74,1447,786],{"class":785},[74,1449,1450],{"class":781},"getCookie",[74,1452,786],{"class":785},[74,1454,1348],{"class":948},[74,1456,1457],{"class":785},") ",[74,1459,1281],{"class":770},[74,1461,1462],{"class":948}," ''",[74,1464,1465],{"class":785},"),\n",[74,1467,1468],{"class":76,"line":235},[74,1469,1470],{"class":785},"    )\n",[74,1472,1473],{"class":76,"line":241},[74,1474,1055],{"class":785},[74,1476,1477],{"class":76,"line":247},[74,1478,1479],{"class":785},"})\n",[74,1481,1483],{"class":76,"line":1482},31,[74,1484,87],{"emptyLinePlaceholder":86},[74,1486,1488,1491,1493,1495,1497,1499,1502],{"class":76,"line":1487},32,[74,1489,1490],{"class":770},"function",[74,1492,1343],{"class":781},[74,1494,786],{"class":785},[74,1496,350],{"class":1021},[74,1498,1141],{"class":770},[74,1500,1501],{"class":774}," string",[74,1503,1504],{"class":785},") {\n",[74,1506,1508,1511,1514,1516,1519,1522,1524,1527,1530,1532,1535,1537,1540],{"class":76,"line":1507},33,[74,1509,1510],{"class":770},"  const",[74,1512,1513],{"class":774}," match",[74,1515,778],{"class":770},[74,1517,1518],{"class":785}," document.cookie.",[74,1520,1521],{"class":781},"match",[74,1523,786],{"class":785},[74,1525,1526],{"class":770},"new",[74,1528,1529],{"class":781}," RegExp",[74,1531,786],{"class":785},[74,1533,1534],{"class":948},"`(^| )${",[74,1536,350],{"class":785},[74,1538,1539],{"class":948},"}=([^;]+)`",[74,1541,1542],{"class":785},"))\n",[74,1544,1546,1548,1551,1554,1557,1560,1563,1565],{"class":76,"line":1545},34,[74,1547,859],{"class":770},[74,1549,1550],{"class":785}," match ",[74,1552,1553],{"class":770},"?",[74,1555,1556],{"class":785}," match[",[74,1558,1559],{"class":774},"2",[74,1561,1562],{"class":785},"] ",[74,1564,1141],{"class":770},[74,1566,1567],{"class":774}," null\n",[74,1569,1571],{"class":76,"line":1570},35,[74,1572,340],{"class":785},[28,1574,1576],{"id":1575},"auto-import-all-the-things","Auto-import all the things",[10,1578,1579,1580,1583],{},"As in the series configuration, update ",[42,1581,1582],{},".vitepress\u002Fconfig.mts"," to auto-import the new utilities, queries, mutations, and Pinia Colada composables.",[64,1585,1588],{"className":1586,"code":1587,"filename":1582,"language":964,"meta":70,"style":70},"language-ts shiki shiki-themes github-light github-light github-dark has-diff has-highlighted","const currentDir = dirname(fileURLToPath(import.meta.url))\nconst themeDir = resolve(currentDir, 'theme')\n\nconst utilsDir = resolve(themeDir, '**', 'utils') \u002F\u002F [!code ++]\nconst queriesDir = resolve(themeDir, '**', 'queries') \u002F\u002F [!code ++]\nconst mutationsDir = resolve(themeDir, '**', 'mutations') \u002F\u002F [!code ++]\nconst apiFile = resolve(themeDir, '**', 'api.ts') \u002F\u002F [!code ++]\n\nexport default defineConfig({\n  vite: {\n    plugins: [\n      AutoImport({\n        imports: [\n          { \u002F\u002F [!code ++]\n            from: '@pinia\u002Fcolada', \u002F\u002F [!code ++]\n            imports: [ \u002F\u002F [!code ++]\n              'defineQuery', \u002F\u002F [!code ++]\n              'useQuery', \u002F\u002F [!code ++]\n              'defineMutation', \u002F\u002F [!code ++]\n              'useMutation', \u002F\u002F [!code ++]\n              'useQueryCache', \u002F\u002F [!code ++]\n            ], \u002F\u002F [!code ++]\n          }, \u002F\u002F [!code ++]\n        ],\n        dirs: [composablesDir, utilsDir, queriesDir, mutationsDir, apiFile], \u002F\u002F [!code highlight]\n      }),\n    ],\n  },\n})\n",[42,1589,1590,1618,1638,1642,1669,1692,1715,1738,1742,1753,1758,1763,1770,1775,1781,1792,1798,1806,1814,1822,1830,1838,1844,1850,1855,1862,1867,1872,1876],{"__ignoreMap":70},[74,1591,1592,1594,1597,1599,1602,1604,1607,1609,1611,1613,1615],{"class":76,"line":77},[74,1593,771],{"class":770},[74,1595,1596],{"class":774}," currentDir",[74,1598,778],{"class":770},[74,1600,1601],{"class":781}," dirname",[74,1603,786],{"class":785},[74,1605,1606],{"class":781},"fileURLToPath",[74,1608,786],{"class":785},[74,1610,971],{"class":770},[74,1612,1193],{"class":785},[74,1614,1196],{"class":774},[74,1616,1617],{"class":785},".url))\n",[74,1619,1620,1622,1625,1627,1630,1633,1636],{"class":76,"line":83},[74,1621,771],{"class":770},[74,1623,1624],{"class":774}," themeDir",[74,1626,778],{"class":770},[74,1628,1629],{"class":781}," resolve",[74,1631,1632],{"class":785},"(currentDir, ",[74,1634,1635],{"class":948},"'theme'",[74,1637,792],{"class":785},[74,1639,1640],{"class":76,"line":90},[74,1641,87],{"emptyLinePlaceholder":86},[74,1643,1647,1649,1652,1654,1656,1659,1662,1664,1667],{"class":1644,"line":96},[76,1645,1646],"diff","add",[74,1648,771],{"class":770},[74,1650,1651],{"class":774}," utilsDir",[74,1653,778],{"class":770},[74,1655,1629],{"class":781},[74,1657,1658],{"class":785},"(themeDir, ",[74,1660,1661],{"class":948},"'**'",[74,1663,351],{"class":785},[74,1665,1666],{"class":948},"'utils'",[74,1668,1457],{"class":785},[74,1670,1672,1674,1677,1679,1681,1683,1685,1687,1690],{"class":1671,"line":101},[76,1645,1646],[74,1673,771],{"class":770},[74,1675,1676],{"class":774}," queriesDir",[74,1678,778],{"class":770},[74,1680,1629],{"class":781},[74,1682,1658],{"class":785},[74,1684,1661],{"class":948},[74,1686,351],{"class":785},[74,1688,1689],{"class":948},"'queries'",[74,1691,1457],{"class":785},[74,1693,1695,1697,1700,1702,1704,1706,1708,1710,1713],{"class":1694,"line":107},[76,1645,1646],[74,1696,771],{"class":770},[74,1698,1699],{"class":774}," mutationsDir",[74,1701,778],{"class":770},[74,1703,1629],{"class":781},[74,1705,1658],{"class":785},[74,1707,1661],{"class":948},[74,1709,351],{"class":785},[74,1711,1712],{"class":948},"'mutations'",[74,1714,1457],{"class":785},[74,1716,1718,1720,1723,1725,1727,1729,1731,1733,1736],{"class":1717,"line":112},[76,1645,1646],[74,1719,771],{"class":770},[74,1721,1722],{"class":774}," apiFile",[74,1724,778],{"class":770},[74,1726,1629],{"class":781},[74,1728,1658],{"class":785},[74,1730,1661],{"class":948},[74,1732,351],{"class":785},[74,1734,1735],{"class":948},"'api.ts'",[74,1737,1457],{"class":785},[74,1739,1740],{"class":76,"line":118},[74,1741,87],{"emptyLinePlaceholder":86},[74,1743,1744,1746,1748,1751],{"class":76,"line":124},[74,1745,801],{"class":770},[74,1747,1003],{"class":770},[74,1749,1750],{"class":781}," defineConfig",[74,1752,1183],{"class":785},[74,1754,1755],{"class":76,"line":130},[74,1756,1757],{"class":785},"  vite: {\n",[74,1759,1760],{"class":76,"line":136},[74,1761,1762],{"class":785},"    plugins: [\n",[74,1764,1765,1768],{"class":76,"line":141},[74,1766,1767],{"class":781},"      AutoImport",[74,1769,1183],{"class":785},[74,1771,1772],{"class":76,"line":147},[74,1773,1774],{"class":785},"        imports: [\n",[74,1776,1778],{"class":1777,"line":153},[76,1645,1646],[74,1779,1780],{"class":785},"          { ",[74,1782,1784,1787,1790],{"class":1783,"line":158},[76,1645,1646],[74,1785,1786],{"class":785},"            from: ",[74,1788,1789],{"class":948},"'@pinia\u002Fcolada'",[74,1791,351],{"class":785},[74,1793,1795],{"class":1794,"line":164},[76,1645,1646],[74,1796,1797],{"class":785},"            imports: [ ",[74,1799,1801,1804],{"class":1800,"line":170},[76,1645,1646],[74,1802,1803],{"class":948},"              'defineQuery'",[74,1805,351],{"class":785},[74,1807,1809,1812],{"class":1808,"line":175},[76,1645,1646],[74,1810,1811],{"class":948},"              'useQuery'",[74,1813,351],{"class":785},[74,1815,1817,1820],{"class":1816,"line":181},[76,1645,1646],[74,1818,1819],{"class":948},"              'defineMutation'",[74,1821,351],{"class":785},[74,1823,1825,1828],{"class":1824,"line":187},[76,1645,1646],[74,1826,1827],{"class":948},"              'useMutation'",[74,1829,351],{"class":785},[74,1831,1833,1836],{"class":1832,"line":193},[76,1645,1646],[74,1834,1835],{"class":948},"              'useQueryCache'",[74,1837,351],{"class":785},[74,1839,1841],{"class":1840,"line":199},[76,1645,1646],[74,1842,1843],{"class":785},"            ], ",[74,1845,1847],{"class":1846,"line":205},[76,1645,1646],[74,1848,1849],{"class":785},"          }, ",[74,1851,1852],{"class":76,"line":211},[74,1853,1854],{"class":785},"        ],\n",[74,1856,1859],{"class":1857,"line":217},[76,1858],"highlighted",[74,1860,1861],{"class":785},"        dirs: [composablesDir, utilsDir, queriesDir, mutationsDir, apiFile], ",[74,1863,1864],{"class":76,"line":223},[74,1865,1866],{"class":785},"      }),\n",[74,1868,1869],{"class":76,"line":229},[74,1870,1871],{"class":785},"    ],\n",[74,1873,1874],{"class":76,"line":235},[74,1875,1055],{"class":785},[74,1877,1878],{"class":76,"line":241},[74,1879,1479],{"class":785},[10,1881,1882,1883,351,1886,355,1888,1890],{},"This makes every function exported from the ",[42,1884,1885],{},"utils",[42,1887,1097],{},[42,1889,1106],{}," folders available throughout the application.",[28,1892,1894],{"id":1893},"creating-the-user-feature","Creating the user feature",[10,1896,1897],{},"Now, it's time to follow our plan:",[10,1899,1900,1901,1903],{},"Create the ",[42,1902,1122],{}," feature:",[64,1905,1907],{"className":935,"code":1906,"filename":937,"language":938,"meta":70,"style":70},"mkdir -p .vitepress\u002Ftheme\u002Fuser\u002F{queries,mutations}\ntouch .vitepress\u002Ftheme\u002Fuser\u002Fapi.ts\n",[42,1908,1909,1920],{"__ignoreMap":70},[74,1910,1911,1914,1917],{"class":76,"line":77},[74,1912,1913],{"class":781},"mkdir",[74,1915,1916],{"class":774}," -p",[74,1918,1919],{"class":948}," .vitepress\u002Ftheme\u002Fuser\u002F{queries,mutations}\n",[74,1921,1922,1925],{"class":76,"line":83},[74,1923,1924],{"class":781},"touch",[74,1926,1927],{"class":948}," .vitepress\u002Ftheme\u002Fuser\u002Fapi.ts\n",[10,1929,1930,1931,366],{},"Then, we can write the code to fetch the user data and to logout the user in the ",[42,1932,1933],{},".vitepress\u002Ftheme\u002Fuser\u002Fapi.ts",[64,1935,1937],{"className":961,"code":1936,"filename":1933,"language":964,"meta":70,"style":70},"export const fetchUser = () => api('api\u002Fuser')\n\nexport const postLogoutUser = () => api('logout', { method: 'POST' })\n",[42,1938,1939,1964,1968],{"__ignoreMap":70},[74,1940,1941,1943,1945,1948,1950,1953,1955,1957,1959,1962],{"class":76,"line":77},[74,1942,801],{"class":770},[74,1944,1169],{"class":770},[74,1946,1947],{"class":781}," fetchUser",[74,1949,778],{"class":770},[74,1951,1952],{"class":785}," () ",[74,1954,1257],{"class":770},[74,1956,1172],{"class":781},[74,1958,786],{"class":785},[74,1960,1961],{"class":948},"'api\u002Fuser'",[74,1963,792],{"class":785},[74,1965,1966],{"class":76,"line":83},[74,1967,87],{"emptyLinePlaceholder":86},[74,1969,1970,1972,1974,1977,1979,1981,1983,1985,1987,1990,1993,1996],{"class":76,"line":90},[74,1971,801],{"class":770},[74,1973,1169],{"class":770},[74,1975,1976],{"class":781}," postLogoutUser",[74,1978,778],{"class":770},[74,1980,1952],{"class":785},[74,1982,1257],{"class":770},[74,1984,1172],{"class":781},[74,1986,786],{"class":785},[74,1988,1989],{"class":948},"'logout'",[74,1991,1992],{"class":785},", { method: ",[74,1994,1995],{"class":948},"'POST'",[74,1997,1998],{"class":785}," })\n",[10,2000,2001,2002,2005,2006,2009],{},"These functions abstract the raw API calls. The rest of the feature can use the explicit names ",[42,2003,2004],{},"fetchUser"," and ",[42,2007,2008],{},"postLogoutUser"," without knowing the request details.",[644,2011,2012],{"color":646,"icon":647},[10,2013,2014,2015,2017],{},"How do I name API functions? I use the ",[42,2016,899],{}," prefix for queries, followed by the resource name. For mutations, I use the HTTP verb followed by the resource name. This makes the functions easy to recognize and remember.",[10,2019,2020],{},"Now, we can create the query used to fetch the user data:",[64,2022,2025],{"className":961,"code":2023,"filename":2024,"language":964,"meta":70,"style":70},"import type { User } from '@\u002Fuser\u002Ftypes\u002Fuser'\n\nexport const useUser = defineQuery(() => {\n  return useQuery\u003CUser>({\n    key: ['user'],\n    query: () => fetchUser().then(response => response.data),\n    enabled: typeof document !== 'undefined',\n  })\n})\n",".vitepress\u002Ftheme\u002Fuser\u002Fqueries\u002Fusers.ts",[42,2026,2027,2042,2046,2066,2082,2093,2122,2141,2146],{"__ignoreMap":70},[74,2028,2029,2031,2034,2037,2039],{"class":76,"line":77},[74,2030,971],{"class":770},[74,2032,2033],{"class":770}," type",[74,2035,2036],{"class":785}," { User } ",[74,2038,977],{"class":770},[74,2040,2041],{"class":948}," '@\u002Fuser\u002Ftypes\u002Fuser'\n",[74,2043,2044],{"class":76,"line":83},[74,2045,87],{"emptyLinePlaceholder":86},[74,2047,2048,2050,2052,2054,2056,2059,2062,2064],{"class":76,"line":90},[74,2049,801],{"class":770},[74,2051,1169],{"class":770},[74,2053,807],{"class":774},[74,2055,778],{"class":770},[74,2057,2058],{"class":781}," defineQuery",[74,2060,2061],{"class":785},"(() ",[74,2063,1257],{"class":770},[74,2065,862],{"class":785},[74,2067,2068,2070,2073,2076,2079],{"class":76,"line":96},[74,2069,859],{"class":770},[74,2071,2072],{"class":781}," useQuery",[74,2074,2075],{"class":785},"\u003C",[74,2077,2078],{"class":781},"User",[74,2080,2081],{"class":785},">({\n",[74,2083,2084,2087,2090],{"class":76,"line":101},[74,2085,2086],{"class":785},"    key: [",[74,2088,2089],{"class":948},"'user'",[74,2091,2092],{"class":785},"],\n",[74,2094,2095,2098,2101,2103,2105,2108,2111,2113,2116,2119],{"class":76,"line":107},[74,2096,2097],{"class":781},"    query",[74,2099,2100],{"class":785},": () ",[74,2102,1257],{"class":770},[74,2104,1947],{"class":781},[74,2106,2107],{"class":785},"().",[74,2109,2110],{"class":781},"then",[74,2112,786],{"class":785},[74,2114,2115],{"class":1021},"response",[74,2117,2118],{"class":770}," =>",[74,2120,2121],{"class":785}," response.data),\n",[74,2123,2124,2127,2130,2133,2136,2139],{"class":76,"line":112},[74,2125,2126],{"class":785},"    enabled: ",[74,2128,2129],{"class":770},"typeof",[74,2131,2132],{"class":785}," document ",[74,2134,2135],{"class":770},"!==",[74,2137,2138],{"class":948}," 'undefined'",[74,2140,1205],{"class":785},[74,2142,2143],{"class":76,"line":118},[74,2144,2145],{"class":785},"  })\n",[74,2147,2148],{"class":76,"line":124},[74,2149,1479],{"class":785},[10,2151,2152],{},"We also need to define a new type for the user:",[64,2154,2157],{"className":961,"code":2155,"filename":2156,"language":964,"meta":70,"style":70},"export interface User {\n  id: number\n  name: string\n  username: string\n  avatar: string\n}\n",".vitepress\u002Ftheme\u002Fuser\u002Ftypes\u002Fuser.ts",[42,2158,2159,2171,2181,2191,2200,2209],{"__ignoreMap":70},[74,2160,2161,2163,2166,2169],{"class":76,"line":77},[74,2162,801],{"class":770},[74,2164,2165],{"class":770}," interface",[74,2167,2168],{"class":781}," User",[74,2170,862],{"class":785},[74,2172,2173,2176,2178],{"class":76,"line":83},[74,2174,2175],{"class":1021},"  id",[74,2177,1141],{"class":770},[74,2179,2180],{"class":774}," number\n",[74,2182,2183,2186,2188],{"class":76,"line":90},[74,2184,2185],{"class":1021},"  name",[74,2187,1141],{"class":770},[74,2189,2190],{"class":774}," string\n",[74,2192,2193,2196,2198],{"class":76,"line":96},[74,2194,2195],{"class":1021},"  username",[74,2197,1141],{"class":770},[74,2199,2190],{"class":774},[74,2201,2202,2205,2207],{"class":76,"line":101},[74,2203,2204],{"class":1021},"  avatar",[74,2206,1141],{"class":770},[74,2208,2190],{"class":774},[74,2210,2211],{"class":76,"line":107},[74,2212,340],{"class":785},[10,2214,2215],{},"Here is how the query works:",[922,2217,2218,2224,2230,2240,2252],{},[39,2219,2220,2223],{},[42,2221,2222],{},"defineQuery"," defines a reusable query within the Vue context.",[39,2225,2226,2229],{},[42,2227,2228],{},"useQuery"," describes the key, request function, and state returned to components.",[39,2231,2232,2235,2236,2239],{},[42,2233,2234],{},"key"," identifies the query in Pinia Colada's cache. When ",[42,2237,2238],{},"useUser"," is called again, Pinia Colada can reuse a fresh cached result instead of sending another request.",[39,2241,2242,2245,2246,2249,2250,1193],{},[42,2243,2244],{},"query"," returns the promise for the API request. We return the response's ",[42,2247,2248],{},"data"," property because Laravel resources wrap their payload in ",[42,2251,2248],{},[39,2253,2254,2257],{},[42,2255,2256],{},"enabled"," limits the request to the browser. We do not want to call the API while VitePress is generating the site.",[10,2259,2260,2261,2263],{},"We can now call ",[42,2262,2238],{}," anywhere in the application. Components do not need to await the request; they consume its reactive state and let Vue update the interface when the data arrives.",[10,2265,2266],{},"Pinia Colada also deduplicates requests, refetches stale data when needed, exposes the cache, and provides hooks for optimistic updates.",[644,2268,2269],{"color":646,"icon":647},[10,2270,2271,2272,2274],{},"Deduplication matters because multiple components can call ",[42,2273,2238],{}," on the same page. Pinia Colada makes one API request and shares the result between those calls.",[10,2276,2277],{},"Then, we can write the mutation to logout the user:",[64,2279,2282],{"className":961,"code":2280,"filename":2281,"language":964,"meta":70,"style":70},"import type { User } from '@\u002Fuser\u002Ftypes\u002Fuser'\n\nexport const useLogoutUser = defineMutation(() => {\n  const queryCache = useQueryCache()\n\n  return useMutation({\n    mutation: () => postLogoutUser(),\n\n    onMutate: () => {\n      const oldUser = queryCache.getQueryData\u003CUser>(['user'])\n\n      queryCache.setQueryData(['user'], null)\n      queryCache.cancelQueries({ key: ['user'], exact: true })\n\n      return { oldUser }\n    },\n    onError: (_, __, { oldUser }) => {\n      if (oldUser) {\n        queryCache.setQueryData(['user'], oldUser)\n      }\n    },\n    onSettled: () =>\n      queryCache.invalidateQueries({ key: ['user'], exact: true }),\n  })\n})\n",".vitepress\u002Ftheme\u002Fuser\u002Fmutations\u002Fusers.ts",[42,2283,2284,2296,2300,2320,2334,2338,2347,2361,2365,2376,2404,2408,2428,2448,2452,2460,2465,2493,2501,2515,2520,2524,2534,2552,2556],{"__ignoreMap":70},[74,2285,2286,2288,2290,2292,2294],{"class":76,"line":77},[74,2287,971],{"class":770},[74,2289,2033],{"class":770},[74,2291,2036],{"class":785},[74,2293,977],{"class":770},[74,2295,2041],{"class":948},[74,2297,2298],{"class":76,"line":83},[74,2299,87],{"emptyLinePlaceholder":86},[74,2301,2302,2304,2306,2309,2311,2314,2316,2318],{"class":76,"line":90},[74,2303,801],{"class":770},[74,2305,1169],{"class":770},[74,2307,2308],{"class":774}," useLogoutUser",[74,2310,778],{"class":770},[74,2312,2313],{"class":781}," defineMutation",[74,2315,2061],{"class":785},[74,2317,1257],{"class":770},[74,2319,862],{"class":785},[74,2321,2322,2324,2327,2329,2332],{"class":76,"line":96},[74,2323,1510],{"class":770},[74,2325,2326],{"class":774}," queryCache",[74,2328,778],{"class":770},[74,2330,2331],{"class":781}," useQueryCache",[74,2333,845],{"class":785},[74,2335,2336],{"class":76,"line":101},[74,2337,87],{"emptyLinePlaceholder":86},[74,2339,2340,2342,2345],{"class":76,"line":107},[74,2341,859],{"class":770},[74,2343,2344],{"class":781}," useMutation",[74,2346,1183],{"class":785},[74,2348,2349,2352,2354,2356,2358],{"class":76,"line":112},[74,2350,2351],{"class":781},"    mutation",[74,2353,2100],{"class":785},[74,2355,1257],{"class":770},[74,2357,1976],{"class":781},[74,2359,2360],{"class":785},"(),\n",[74,2362,2363],{"class":76,"line":118},[74,2364,87],{"emptyLinePlaceholder":86},[74,2366,2367,2370,2372,2374],{"class":76,"line":124},[74,2368,2369],{"class":781},"    onMutate",[74,2371,2100],{"class":785},[74,2373,1257],{"class":770},[74,2375,862],{"class":785},[74,2377,2378,2381,2384,2386,2389,2392,2394,2396,2399,2401],{"class":76,"line":130},[74,2379,2380],{"class":770},"      const",[74,2382,2383],{"class":774}," oldUser",[74,2385,778],{"class":770},[74,2387,2388],{"class":785}," queryCache.",[74,2390,2391],{"class":781},"getQueryData",[74,2393,2075],{"class":785},[74,2395,2078],{"class":781},[74,2397,2398],{"class":785},">([",[74,2400,2089],{"class":948},[74,2402,2403],{"class":785},"])\n",[74,2405,2406],{"class":76,"line":136},[74,2407,87],{"emptyLinePlaceholder":86},[74,2409,2410,2413,2416,2419,2421,2424,2426],{"class":76,"line":141},[74,2411,2412],{"class":785},"      queryCache.",[74,2414,2415],{"class":781},"setQueryData",[74,2417,2418],{"class":785},"([",[74,2420,2089],{"class":948},[74,2422,2423],{"class":785},"], ",[74,2425,789],{"class":774},[74,2427,792],{"class":785},[74,2429,2430,2432,2435,2438,2440,2443,2446],{"class":76,"line":147},[74,2431,2412],{"class":785},[74,2433,2434],{"class":781},"cancelQueries",[74,2436,2437],{"class":785},"({ key: [",[74,2439,2089],{"class":948},[74,2441,2442],{"class":785},"], exact: ",[74,2444,2445],{"class":774},"true",[74,2447,1998],{"class":785},[74,2449,2450],{"class":76,"line":153},[74,2451,87],{"emptyLinePlaceholder":86},[74,2453,2454,2457],{"class":76,"line":158},[74,2455,2456],{"class":770},"      return",[74,2458,2459],{"class":785}," { oldUser }\n",[74,2461,2462],{"class":76,"line":164},[74,2463,2464],{"class":785},"    },\n",[74,2466,2467,2470,2473,2476,2478,2481,2484,2487,2489,2491],{"class":76,"line":170},[74,2468,2469],{"class":781},"    onError",[74,2471,2472],{"class":785},": (",[74,2474,2475],{"class":1021},"_",[74,2477,351],{"class":785},[74,2479,2480],{"class":1021},"__",[74,2482,2483],{"class":785},", { ",[74,2485,2486],{"class":1021},"oldUser",[74,2488,1254],{"class":785},[74,2490,1257],{"class":770},[74,2492,862],{"class":785},[74,2494,2495,2498],{"class":76,"line":175},[74,2496,2497],{"class":770},"      if",[74,2499,2500],{"class":785}," (oldUser) {\n",[74,2502,2503,2506,2508,2510,2512],{"class":76,"line":181},[74,2504,2505],{"class":785},"        queryCache.",[74,2507,2415],{"class":781},[74,2509,2418],{"class":785},[74,2511,2089],{"class":948},[74,2513,2514],{"class":785},"], oldUser)\n",[74,2516,2517],{"class":76,"line":187},[74,2518,2519],{"class":785},"      }\n",[74,2521,2522],{"class":76,"line":193},[74,2523,2464],{"class":785},[74,2525,2526,2529,2531],{"class":76,"line":199},[74,2527,2528],{"class":781},"    onSettled",[74,2530,2100],{"class":785},[74,2532,2533],{"class":770},"=>\n",[74,2535,2536,2538,2541,2543,2545,2547,2549],{"class":76,"line":205},[74,2537,2412],{"class":785},[74,2539,2540],{"class":781},"invalidateQueries",[74,2542,2437],{"class":785},[74,2544,2089],{"class":948},[74,2546,2442],{"class":785},[74,2548,2445],{"class":774},[74,2550,2551],{"class":785}," }),\n",[74,2553,2554],{"class":76,"line":211},[74,2555,2145],{"class":785},[74,2557,2558],{"class":76,"line":217},[74,2559,1479],{"class":785},[10,2561,2562,2563,2566,2567,2570,2571,2574],{},"This mutation uses an optimistic update. When the user clicks logout, ",[42,2564,2565],{},"onMutate"," removes the user from the cache immediately, so the interface swaps the logout button for the login button without waiting for the server. It returns the previous user so ",[42,2568,2569],{},"onError"," can restore it if the request fails. ",[42,2572,2573],{},"onSettled"," runs in either case and invalidates the user query, allowing Pinia Colada to refresh it when it is used again.",[10,2576,2577,2578,2580],{},"Update the header to call ",[42,2579,2238],{}," and display the appropriate button:",[64,2582,2587],{"className":2583,"code":2584,"filename":2585,"language":2586,"meta":70,"style":70},"language-vue shiki shiki-themes github-light github-light github-dark","\u003Cscript lang=\"ts\" setup>\nconst { state } = useUser()\n\u003C\u002Fscript>\n\n\u003Ctemplate>\n  \u003Cheader>\n    \u003Cdiv>\n      \u003C!-- ... -->\n      \u003Cdiv>\n        \u003C!-- ... -->\n        \u003CButton v-if=\"state.data\" label=\"Logout\" \u002F>\n        \u003CButton v-else :href=\"loginUrl\" label=\"Login\" \u002F>\n      \u003C\u002Fdiv>\n    \u003C\u002Fdiv>\n  \u003C\u002Fheader>\n\u003C\u002Ftemplate>\n",".vitepress\u002Ftheme\u002Fcommon\u002Fcomponents\u002FTheHeader.vue","vue",[42,2588,2589,2611,2630,2639,2643,2652,2662,2672,2677,2686,2691,2723,2756,2765,2774,2783],{"__ignoreMap":70},[74,2590,2591,2593,2597,2600,2602,2605,2608],{"class":76,"line":77},[74,2592,2075],{"class":785},[74,2594,2596],{"class":2595},"sovSZ","script",[74,2598,2599],{"class":781}," lang",[74,2601,836],{"class":785},[74,2603,2604],{"class":948},"\"ts\"",[74,2606,2607],{"class":781}," setup",[74,2609,2610],{"class":785},">\n",[74,2612,2613,2615,2618,2621,2624,2626,2628],{"class":76,"line":83},[74,2614,771],{"class":770},[74,2616,2617],{"class":785}," { ",[74,2619,2620],{"class":774},"state",[74,2622,2623],{"class":785}," } ",[74,2625,836],{"class":770},[74,2627,807],{"class":781},[74,2629,845],{"class":785},[74,2631,2632,2635,2637],{"class":76,"line":90},[74,2633,2634],{"class":785},"\u003C\u002F",[74,2636,2596],{"class":2595},[74,2638,2610],{"class":785},[74,2640,2641],{"class":76,"line":96},[74,2642,87],{"emptyLinePlaceholder":86},[74,2644,2645,2647,2650],{"class":76,"line":101},[74,2646,2075],{"class":785},[74,2648,2649],{"class":2595},"template",[74,2651,2610],{"class":785},[74,2653,2654,2657,2660],{"class":76,"line":107},[74,2655,2656],{"class":785},"  \u003C",[74,2658,2659],{"class":2595},"header",[74,2661,2610],{"class":785},[74,2663,2664,2667,2670],{"class":76,"line":112},[74,2665,2666],{"class":785},"    \u003C",[74,2668,2669],{"class":2595},"div",[74,2671,2610],{"class":785},[74,2673,2674],{"class":76,"line":118},[74,2675,2676],{"class":827},"      \u003C!-- ... -->\n",[74,2678,2679,2682,2684],{"class":76,"line":124},[74,2680,2681],{"class":785},"      \u003C",[74,2683,2669],{"class":2595},[74,2685,2610],{"class":785},[74,2687,2688],{"class":76,"line":130},[74,2689,2690],{"class":827},"        \u003C!-- ... -->\n",[74,2692,2693,2696,2699,2702,2704,2707,2710,2712,2715,2717,2720],{"class":76,"line":136},[74,2694,2695],{"class":785},"        \u003C",[74,2697,2698],{"class":2595},"Button",[74,2700,2701],{"class":770}," v-if",[74,2703,836],{"class":785},[74,2705,2706],{"class":948},"\"",[74,2708,2709],{"class":785},"state.data",[74,2711,2706],{"class":948},[74,2713,2714],{"class":781}," label",[74,2716,836],{"class":785},[74,2718,2719],{"class":948},"\"Logout\"",[74,2721,2722],{"class":785}," \u002F>\n",[74,2724,2725,2727,2729,2732,2735,2738,2740,2742,2745,2747,2749,2751,2754],{"class":76,"line":141},[74,2726,2695],{"class":785},[74,2728,2698],{"class":2595},[74,2730,2731],{"class":770}," v-else",[74,2733,2734],{"class":785}," :",[74,2736,2737],{"class":781},"href",[74,2739,836],{"class":785},[74,2741,2706],{"class":948},[74,2743,2744],{"class":785},"loginUrl",[74,2746,2706],{"class":948},[74,2748,2714],{"class":781},[74,2750,836],{"class":785},[74,2752,2753],{"class":948},"\"Login\"",[74,2755,2722],{"class":785},[74,2757,2758,2761,2763],{"class":76,"line":147},[74,2759,2760],{"class":785},"      \u003C\u002F",[74,2762,2669],{"class":2595},[74,2764,2610],{"class":785},[74,2766,2767,2770,2772],{"class":76,"line":153},[74,2768,2769],{"class":785},"    \u003C\u002F",[74,2771,2669],{"class":2595},[74,2773,2610],{"class":785},[74,2775,2776,2779,2781],{"class":76,"line":158},[74,2777,2778],{"class":785},"  \u003C\u002F",[74,2780,2659],{"class":2595},[74,2782,2610],{"class":785},[74,2784,2785,2787,2789],{"class":76,"line":164},[74,2786,2634],{"class":785},[74,2788,2649],{"class":2595},[74,2790,2610],{"class":785},[10,2792,2793],{},"Then, we can add our mutation:",[64,2795,2798],{"className":2796,"code":2797,"filename":762,"language":2586,"meta":70,"style":70},"language-vue shiki shiki-themes github-light github-light github-dark has-diff","\u003Cscript lang=\"ts\" setup>\nconst { mutate: logout } = useLogoutUser()\n\u003C\u002Fscript>\n\n\u003Ctemplate>\n  \u003Cheader>\n    \u003Cdiv>\n      \u003C!-- ... -->\n      \u003Cdiv>\n        \u003C!-- ... -->\n        \u003CButton v-if=\"state.data\" label=\"Logout\" @click=\"logout\" \u002F> \u003C!-- [!code ++] -->\n      \u003C\u002Fdiv>\n    \u003C\u002Fdiv>\n  \u003C\u002Fheader>\n\u003C\u002Ftemplate>\n",[42,2799,2800,2816,2837,2845,2849,2857,2865,2873,2877,2885,2889,2929,2937,2945,2953],{"__ignoreMap":70},[74,2801,2802,2804,2806,2808,2810,2812,2814],{"class":76,"line":77},[74,2803,2075],{"class":785},[74,2805,2596],{"class":2595},[74,2807,2599],{"class":781},[74,2809,836],{"class":785},[74,2811,2604],{"class":948},[74,2813,2607],{"class":781},[74,2815,2610],{"class":785},[74,2817,2818,2820,2822,2825,2827,2829,2831,2833,2835],{"class":76,"line":83},[74,2819,771],{"class":770},[74,2821,2617],{"class":785},[74,2823,2824],{"class":1021},"mutate",[74,2826,1242],{"class":785},[74,2828,705],{"class":774},[74,2830,2623],{"class":785},[74,2832,836],{"class":770},[74,2834,2308],{"class":781},[74,2836,845],{"class":785},[74,2838,2839,2841,2843],{"class":76,"line":90},[74,2840,2634],{"class":785},[74,2842,2596],{"class":2595},[74,2844,2610],{"class":785},[74,2846,2847],{"class":76,"line":96},[74,2848,87],{"emptyLinePlaceholder":86},[74,2850,2851,2853,2855],{"class":76,"line":101},[74,2852,2075],{"class":785},[74,2854,2649],{"class":2595},[74,2856,2610],{"class":785},[74,2858,2859,2861,2863],{"class":76,"line":107},[74,2860,2656],{"class":785},[74,2862,2659],{"class":2595},[74,2864,2610],{"class":785},[74,2866,2867,2869,2871],{"class":76,"line":112},[74,2868,2666],{"class":785},[74,2870,2669],{"class":2595},[74,2872,2610],{"class":785},[74,2874,2875],{"class":76,"line":118},[74,2876,2676],{"class":827},[74,2878,2879,2881,2883],{"class":76,"line":124},[74,2880,2681],{"class":785},[74,2882,2669],{"class":2595},[74,2884,2610],{"class":785},[74,2886,2887],{"class":76,"line":130},[74,2888,2690],{"class":827},[74,2890,2892,2894,2896,2898,2900,2902,2904,2906,2908,2910,2912,2915,2918,2920,2922,2924,2926],{"class":2891,"line":136},[76,1645,1646],[74,2893,2695],{"class":785},[74,2895,2698],{"class":2595},[74,2897,2701],{"class":770},[74,2899,836],{"class":785},[74,2901,2706],{"class":948},[74,2903,2709],{"class":785},[74,2905,2706],{"class":948},[74,2907,2714],{"class":781},[74,2909,836],{"class":785},[74,2911,2719],{"class":948},[74,2913,2914],{"class":785}," @",[74,2916,2917],{"class":781},"click",[74,2919,836],{"class":785},[74,2921,2706],{"class":948},[74,2923,705],{"class":785},[74,2925,2706],{"class":948},[74,2927,2928],{"class":785}," \u002F> ",[74,2930,2931,2933,2935],{"class":76,"line":141},[74,2932,2760],{"class":785},[74,2934,2669],{"class":2595},[74,2936,2610],{"class":785},[74,2938,2939,2941,2943],{"class":76,"line":147},[74,2940,2769],{"class":785},[74,2942,2669],{"class":2595},[74,2944,2610],{"class":785},[74,2946,2947,2949,2951],{"class":76,"line":153},[74,2948,2778],{"class":785},[74,2950,2659],{"class":2595},[74,2952,2610],{"class":785},[74,2954,2955,2957,2959],{"class":76,"line":158},[74,2956,2634],{"class":785},[74,2958,2649],{"class":2595},[74,2960,2610],{"class":785},[10,2962,2963,2964,2966],{},"Try it now, but the logout action will not work yet. Our ",[42,2965,2698],{}," component is currently only a link:",[64,2968,2971],{"className":2583,"code":2969,"filename":2970,"language":2586,"meta":70,"style":70},"\u003Ctemplate>\n  \u003Ca :href :class=\"ui\">\n    {{ props.label }}\n  \u003C\u002Fa>\n\u003C\u002Ftemplate>\n",".vitepress\u002Ftheme\u002Fcommon\u002Fcomponents\u002FButton.vue",[42,2972,2973,2981,3000,3005,3013],{"__ignoreMap":70},[74,2974,2975,2977,2979],{"class":76,"line":77},[74,2976,2075],{"class":785},[74,2978,2649],{"class":2595},[74,2980,2610],{"class":785},[74,2982,2983,2985,2987,2990,2993,2995,2998],{"class":76,"line":83},[74,2984,2656],{"class":785},[74,2986,20],{"class":2595},[74,2988,2989],{"class":781}," :href",[74,2991,2992],{"class":781}," :class",[74,2994,836],{"class":785},[74,2996,2997],{"class":948},"\"ui\"",[74,2999,2610],{"class":785},[74,3001,3002],{"class":76,"line":90},[74,3003,3004],{"class":785},"    {{ props.label }}\n",[74,3006,3007,3009,3011],{"class":76,"line":96},[74,3008,2778],{"class":785},[74,3010,20],{"class":2595},[74,3012,2610],{"class":785},[74,3014,3015,3017,3019],{"class":76,"line":101},[74,3016,2634],{"class":785},[74,3018,2649],{"class":2595},[74,3020,2610],{"class":785},[10,3022,3023,3024,3026,3027,3030,3031,3038],{},"We need a component that renders an anchor when it receives ",[42,3025,2737],{}," and a button when it receives ",[42,3028,3029],{},"onClick",". Vue's built-in ",[20,3032,3035],{"href":3033,"rel":3034},"https:\u002F\u002Fvuejs.org\u002Fapi\u002Fbuilt-in-special-elements#component",[24],[42,3036,3037],{},"component"," element makes this possible.",[10,3040,3041,3042,1141],{},"First, allow the props to accept ",[42,3043,3029],{},[64,3045,3047],{"className":1586,"code":3046,"filename":762,"language":964,"meta":70,"style":70},"export interface ButtonProps {\n  href?: string \u002F\u002F [!code highlight]\n  label: string\n  color?: ButtonVariants['color']\n  class?: any\n  onClick?: () => void \u002F\u002F [!code ++]\n}\n",[42,3048,3049,3060,3071,3080,3099,3109,3124],{"__ignoreMap":70},[74,3050,3051,3053,3055,3058],{"class":76,"line":77},[74,3052,801],{"class":770},[74,3054,2165],{"class":770},[74,3056,3057],{"class":781}," ButtonProps",[74,3059,862],{"class":785},[74,3061,3063,3066,3069],{"class":3062,"line":83},[76,1858],[74,3064,3065],{"class":1021},"  href",[74,3067,3068],{"class":770},"?:",[74,3070,1501],{"class":774},[74,3072,3073,3076,3078],{"class":76,"line":90},[74,3074,3075],{"class":1021},"  label",[74,3077,1141],{"class":770},[74,3079,2190],{"class":774},[74,3081,3082,3085,3087,3090,3093,3096],{"class":76,"line":96},[74,3083,3084],{"class":1021},"  color",[74,3086,3068],{"class":770},[74,3088,3089],{"class":781}," ButtonVariants",[74,3091,3092],{"class":785},"[",[74,3094,3095],{"class":948},"'color'",[74,3097,3098],{"class":785},"]\n",[74,3100,3101,3104,3106],{"class":76,"line":101},[74,3102,3103],{"class":1021},"  class",[74,3105,3068],{"class":770},[74,3107,3108],{"class":774}," any\n",[74,3110,3112,3115,3117,3119,3121],{"class":3111,"line":107},[76,1645,1646],[74,3113,3114],{"class":781},"  onClick",[74,3116,3068],{"class":770},[74,3118,1952],{"class":785},[74,3120,1257],{"class":770},[74,3122,3123],{"class":774}," void",[74,3125,3126],{"class":76,"line":112},[74,3127,340],{"class":785},[10,3129,3130,3131,1141],{},"Then, we can use the built-in special component ",[42,3132,3037],{},[64,3134,3136],{"className":2583,"code":3135,"filename":762,"language":2586,"meta":70,"style":70},"\u003Ctemplate>\n  \u003Ccomponent\n    :is=\"props.href ? 'a' : 'button'\"\n    :href=\"props.href\"\n    :class=\"ui\"\n    @click=\"props.onClick\"\n  >\n    {{ props.label }}\n  \u003C\u002Fcomponent>\n\u003C\u002Ftemplate>\n",[42,3137,3138,3146,3153,3163,3173,3183,3193,3198,3202,3210],{"__ignoreMap":70},[74,3139,3140,3142,3144],{"class":76,"line":77},[74,3141,2075],{"class":785},[74,3143,2649],{"class":2595},[74,3145,2610],{"class":785},[74,3147,3148,3150],{"class":76,"line":83},[74,3149,2656],{"class":785},[74,3151,3152],{"class":2595},"component\n",[74,3154,3155,3158,3160],{"class":76,"line":90},[74,3156,3157],{"class":781},"    :is",[74,3159,836],{"class":785},[74,3161,3162],{"class":948},"\"props.href ? 'a' : 'button'\"\n",[74,3164,3165,3168,3170],{"class":76,"line":96},[74,3166,3167],{"class":781},"    :href",[74,3169,836],{"class":785},[74,3171,3172],{"class":948},"\"props.href\"\n",[74,3174,3175,3178,3180],{"class":76,"line":101},[74,3176,3177],{"class":781},"    :class",[74,3179,836],{"class":785},[74,3181,3182],{"class":948},"\"ui\"\n",[74,3184,3185,3188,3190],{"class":76,"line":107},[74,3186,3187],{"class":781},"    @click",[74,3189,836],{"class":785},[74,3191,3192],{"class":948},"\"props.onClick\"\n",[74,3194,3195],{"class":76,"line":112},[74,3196,3197],{"class":785},"  >\n",[74,3199,3200],{"class":76,"line":118},[74,3201,3004],{"class":785},[74,3203,3204,3206,3208],{"class":76,"line":124},[74,3205,2778],{"class":785},[74,3207,3037],{"class":2595},[74,3209,2610],{"class":785},[74,3211,3212,3214,3216],{"class":76,"line":130},[74,3213,2634],{"class":785},[74,3215,2649],{"class":2595},[74,3217,2610],{"class":785},[10,3219,3220,3221,3224],{},"The important line is ",[42,3222,3223],{},":is=\"props.href ? 'a' : 'button'",": it chooses an anchor or a button based on the props.",[10,3226,3227],{},"Now the complete flow works:",[36,3229,3230,3233,3236],{},[39,3231,3232],{},"Users can log in using GitHub",[39,3234,3235],{},"Users can log out smoothly from the frontend",[39,3237,3238],{},"Users can log in again",[28,3240,3242],{"id":3241},"conclusion","Conclusion",[10,3244,3245],{},"Authentication is now a reusable frontend feature. The application can fetch the current user, share the cached result across components, and update the interface optimistically when the user logs out.",[10,3247,3248],{},"This gives the comment system everything it needs to know whether someone is signed in and which controls to display. In the final article, we will use the same feature-based Pinia Colada structure to list, create, edit, and delete comments.",[3250,3251,3252],"style",{},"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 .s8jYJ, html code.shiki .s8jYJ{--shiki-light:#D73A49;--shiki-default:#D73A49;--shiki-dark:#F97583}html pre.shiki code .sBjJW, html code.shiki .sBjJW{--shiki-light:#005CC5;--shiki-default:#005CC5;--shiki-dark:#79B8FF}html pre.shiki code .snPdu, html code.shiki .snPdu{--shiki-light:#6F42C1;--shiki-default:#6F42C1;--shiki-dark:#B392F0}html pre.shiki code .sxrX7, html code.shiki .sxrX7{--shiki-light:#24292E;--shiki-default:#24292E;--shiki-dark:#E1E4E8}html pre.shiki code .sCsY4, html code.shiki .sCsY4{--shiki-light:#6A737D;--shiki-default:#6A737D;--shiki-dark:#6A737D}html pre.shiki code .sIIMD, html code.shiki .sIIMD{--shiki-light:#032F62;--shiki-default:#032F62;--shiki-dark:#9ECBFF}html pre.shiki code .sP4rz, html code.shiki .sP4rz{--shiki-light:#E36209;--shiki-default:#E36209;--shiki-dark:#FFAB70}html pre.shiki code .sovSZ, html code.shiki .sovSZ{--shiki-light:#22863A;--shiki-default:#22863A;--shiki-dark:#85E89D}",{"title":70,"searchDepth":83,"depth":83,"links":3254},[3255,3259,3260,3261,3262,3263],{"id":30,"depth":83,"text":31,"children":3256},[3257,3258],{"id":58,"depth":90,"text":59},{"id":430,"depth":90,"text":431},{"id":744,"depth":83,"text":745},{"id":1130,"depth":83,"text":1131},{"id":1575,"depth":83,"text":1576},{"id":1893,"depth":83,"text":1894},{"id":3241,"depth":83,"text":3242},"d507f8af-7c76-4660-859e-23af11c0728e","2025-02-25","Connect frontend authentication to Laravel with a current-user query, GitHub logout flow, Pinia Colada caching, and optimistic state updates.","md",null,{},"\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fstreamlining-user-authentication-from-frontend-to-backend","---\ncontentId: d507f8af-7c76-4660-859e-23af11c0728e\npart: 7\ntitle: Streamlining User Authentication from Frontend to Backend\ndescription: Connect frontend authentication to Laravel with a current-user query, GitHub logout flow, Pinia Colada caching, and optimistic state updates.\ndate: 2025-02-25\nseriesSlug: empower-and-dynamize-our-vitepress-blog-with-a-laravel-api\n---\n\nNow that the frontend can reach the Laravel API, we can use that connection to manage authentication throughout the application.\n\nSo far, we have tested requests in isolation. In this article, we will fetch the current user when the application starts, display the appropriate login or logout action, and implement logout with an optimistic update. The interface will update immediately while the API request runs, then recover if the request fails.\n\nTo manage this cleanly, we will combine Pinia with Pinia Colada, a data-fetching library built on top of Pinia and created by [Eduardo](https:\u002F\u002Fgithub.com\u002Fposva), the creator of Pinia. It will give us shared cached state, request status, and the mutation hooks we need for optimistic updates.\n\n## Setting up the API\n\nTo support the frontend, we need two new routes in the Laravel application:\n\n1. `GET \u002Fapi\u002Fuser`: Returns the authenticated user. The frontend calls it when the application starts to adapt the interface.\n2. `POST \u002Flogout`: Logs out the user and invalidates the current session when the frontend's logout button is clicked.\n\nFor each route, we will write tests, create a controller method, and register the route. This follows the same process as the previous articles.\n\n### Returning the user\n\nLet's start with the first route. We will create a test to check if the user is authenticated and if the user data is returned correctly.\n\n```php [tests\u002FHttp\u002FAuth\u002FAuthenticationSessionTest.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nuse Illuminate\\Testing\\Fluent\\AssertableJson;\n\nit('requires authentification', function () {\n    $this->getJson(route('user.show'))\n        ->assertUnauthorized();\n});\n\nit('returns the authenticated user', function () {\n    $user = App\\Models\\User::factory()->create();\n\n    $response = $this->actingAs($user)\n        ->getJson(route('user.show'));\n\n    $response\n        ->assertOk()\n        ->assertJson(\n            fn (AssertableJson $json) => $json\n                ->has(\n                    'data',\n                    fn (AssertableJson $json) => $json\n                        ->where('name', $user->name)\n                        ->where('username', $user->username)\n                        ->where('avatar', $user->avatar)\n                )\n        );\n});\n```\n\nThese tests are similar to the comment tests. The first verifies authentication, and the second checks the user data in the JSON response.\n\nNow, let's create the controller:\n\n```php [app\u002FHttp\u002FControllers\u002FAuth\u002FAuthenticatedSessionController.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Controllers\\Api;\n\nuse App\\Http\\Resources\\UserResource;\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Http\\Resources\\Json\\JsonResource;\n\nfinal class UserController\n{\n    public function show(Request $request): JsonResource\n    {\n        return UserResource::make($request->user());\n    }\n}\n```\n\nThis controller uses `UserResource` to transform the authenticated user into a JSON response. We created that resource in the comment-system article; it exposes the `name`, `username`, and `avatar` fields.\n\nFinally, we need to register the route in the `routes\u002Fapi.php` file:\n\n```php [routes\u002Fapi.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Http\\Controllers\\Api\\UserController;\n\nRoute::middleware('auth:sanctum')->group(function () {\n    Route::get('\u002Fuser', [UserController::class, 'show'])\n        ->name('user.show');\n\n    \u002F\u002F ...\n});\n```\n\nThat is enough to retrieve the current user.\n\n### Logging out the user\n\nLet's get started with the tests:\n\n```php [tests\u002FHttp\u002FAuth\u002FAuthenticationSessionTest.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nuse App\\Models\\User;\n\nit('requires authentification', function () {\n    $this->postJson(route('logout'))\n        ->assertUnauthorized();\n});\n\nit('destroys the session', function () {\n    $response = $this->actingAs(User::factory()->create())\n        ->post(route('logout'))\n        ->assertNoContent();\n\n    $this->assertGuest('web');\n    $response->assertNoContent();\n});\n```\n\nThese tests follow the same patterns as the previous ones.\n\nNow, let's create the controller:\n\n```php [app\u002FHttp\u002FControllers\u002FAuth\u002FAuthenticationSessionController.php]\n\u003C?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Http\\Controllers\\Auth;\n\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Http\\Response;\nuse Illuminate\\Support\\Facades\\Auth;\n\nfinal class AuthenticatedSessionController\n{\n    public function destroy(Request $request): Response\n    {\n        Auth::guard('web')->logout();\n\n        $request->session()->invalidate();\n\n        $request->session()->regenerateToken();\n\n        return response()->noContent();\n    }\n}\n```\n\nThe controller uses Laravel's `Auth` facade to log out the user. It then invalidates the session and regenerates the CSRF token. These steps help prevent session-fixation attacks.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nThe controller returns an empty response because the frontend does not need a response body for logout.\n::\n\nFinally, we need to register the route in the `routes\u002Fweb.php` file:\n\n```php [routes\u002Fweb.php]\nuse App\\Http\\Controllers\\Auth\\AuthenticatedSessionController;\n\nRoute::post('logout', [AuthenticatedSessionController::class, 'destroy'])\n    ->middleware('auth:sanctum')\n    ->name('logout');\n```\n\nThis route uses the `auth:sanctum` middleware even though it is defined in `web.php`. It does not return JSON and does not need to be versioned with the other API routes, so keeping it as a web route is reasonable.\n\nIn the `config\u002Fcors.php` config file, we also need to add the `logout` route to the `paths` array:\n\n```php [config\u002Fcors.php]\nreturn [\n    'paths' => ['api\u002F*', 'logout'],\n\n    \u002F\u002F ...\n];\n```\n\nThis allows the frontend to call the route from a different origin. Without it, the browser would block the request because of CORS.\n\n## Preparing the frontend\n\nThe backend is ready, so we can move to the frontend.\n\nWe will retrieve the user when the application starts so the interface can react to the authentication state. Several components need this information. The header currently displays a login button; we will add a logout button for authenticated users and hide the login button in that case.\n\nThe footer may also need a login or logout link, and the comment system will need the same state to decide whether to display a login button or a comment form.\n\nThe simplest solution would be a shared composable:\n\n```js [Example]\nconst user = ref(null)\n\nexport function useUser() {\n  async function fetch() {\n    \u002F\u002F Simulate fetching user data from the backend\n    user.value = await fetchUserData()\n  }\n\n  return {\n    user,\n    fetch,\n  }\n}\n```\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nWe could also use the [`createSharedComposable`](https:\u002F\u002Fvueuse.org\u002Fshared\u002FcreateSharedComposable\u002F#createsharedcomposable) from Vueuse to avoid having global state while keeping the same instance of the composable in all components.\n::\n\nWe would then call `fetch` in the `onMounted` hook of the main component, `Layout.vue` in our case.\n\nThis solution works for a while, but it quickly becomes difficult to maintain. One component performs the fetch while many others consume the result. That may be manageable for one data type, but it becomes messy as the application grows.\n\nWe would also need boilerplate to manage mutation state. Logging out, creating a comment, and deleting a comment all need loading and error states. Repeating this code would either make components noisy or push us toward a collection of custom utilities.\n\nWe may also want optimistic updates. Logout is a good example: remove the user from state immediately, call the API, and restore the user if the request fails. Implementing that reliably and generically is not trivial.\n\nTo avoid this boilerplate, we will combine Pinia with Pinia Colada.\n\n- Pinia is Vue's state-management library. A store centralizes state, getters, and actions, while the UI reacts to changes in that state.\n- Pinia Colada is a data-fetching library built on top of Pinia. It manages requests and cache state, and it provides the hooks we need for optimistic updates.\n\nInstall Pinia and Pinia Colada in the Garabit project:\n\n```bash [terminal]\npnpm install pinia @pinia\u002Fcolada\n```\n\nThen, we need to register them in our Vue application:\n\n```ts [.vitepress\u002Ftheme\u002Findex.ts]\nimport { PiniaColada } from '@pinia\u002Fcolada'\nimport { createPinia } from 'pinia'\n\nexport default {\n  Layout,\n  enhanceApp({ app }) {\n    app.use(createPinia())\n    app.use(PiniaColada)\n  },\n} satisfies Theme\n```\n\nBoth packages are Vue plugins that add application-level functionality.\n\nRemove the temporary request code from `.vitepress\u002Ftheme\u002FLayout.vue`; the shared API client will replace it.\n\nBefore writing the feature code, let us define the structure. In `common\u002Futils\u002Fapi.ts`, we will create a custom `ofetch` instance so every request uses the same host, headers, credentials, and CSRF handling. This is the code we introduced in the previous article.\n\nEach feature will contain two folders and one API file:\n\n1. `queries`: Contains requests that retrieve data. `GET \u002Fapi\u002Fuser` is a query.\n2. `mutations`: Contains requests that modify data. `POST \u002Flogout` is a mutation.\n3. `api.ts`: Contains the low-level functions that make the requests. This file stays independent of the state-management library, which keeps the API layer easy to read and test.\n\nThese folders and the API file will exist for each feature. Today we will create the `user` feature. The next article will add a `comments` feature. This separation keeps related code together and makes it easier to find.\n\n## Extending ofetch\n\nCreate the custom `ofetch` instance in `.vitepress\u002Ftheme\u002Fcommon\u002Futils\u002Fapi.ts`:\n\n```ts [.vitepress\u002Ftheme\u002Fcommon\u002Futils\u002Fapi.ts]\nimport { ofetch } from 'ofetch'\n\nexport const api = ofetch.create({\n  baseURL: import.meta.env.VITE_API_URL,\n  headers: {\n    Accept: 'application\u002Fjson',\n  },\n  credentials: 'include',\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(\n      'X-Xsrf-Token',\n      decodeURIComponent(getCookie('XSRF-TOKEN') || ''),\n    )\n  },\n})\n\nfunction getCookie(name: string) {\n  const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`))\n  return match ? match[2] : null\n}\n```\n\n## Auto-import all the things\n\nAs in the series configuration, update `.vitepress\u002Fconfig.mts` to auto-import the new utilities, queries, mutations, and Pinia Colada composables.\n\n```ts [.vitepress\u002Fconfig.mts]\nconst currentDir = dirname(fileURLToPath(import.meta.url))\nconst themeDir = resolve(currentDir, 'theme')\n\nconst utilsDir = resolve(themeDir, '**', 'utils') \u002F\u002F [!code ++]\nconst queriesDir = resolve(themeDir, '**', 'queries') \u002F\u002F [!code ++]\nconst mutationsDir = resolve(themeDir, '**', 'mutations') \u002F\u002F [!code ++]\nconst apiFile = resolve(themeDir, '**', 'api.ts') \u002F\u002F [!code ++]\n\nexport default defineConfig({\n  vite: {\n    plugins: [\n      AutoImport({\n        imports: [\n          { \u002F\u002F [!code ++]\n            from: '@pinia\u002Fcolada', \u002F\u002F [!code ++]\n            imports: [ \u002F\u002F [!code ++]\n              'defineQuery', \u002F\u002F [!code ++]\n              'useQuery', \u002F\u002F [!code ++]\n              'defineMutation', \u002F\u002F [!code ++]\n              'useMutation', \u002F\u002F [!code ++]\n              'useQueryCache', \u002F\u002F [!code ++]\n            ], \u002F\u002F [!code ++]\n          }, \u002F\u002F [!code ++]\n        ],\n        dirs: [composablesDir, utilsDir, queriesDir, mutationsDir, apiFile], \u002F\u002F [!code highlight]\n      }),\n    ],\n  },\n})\n```\n\nThis makes every function exported from the `utils`, `queries`, and `mutations` folders available throughout the application.\n\n## Creating the user feature\n\nNow, it's time to follow our plan:\n\nCreate the `user` feature:\n\n```bash [terminal]\nmkdir -p .vitepress\u002Ftheme\u002Fuser\u002F{queries,mutations}\ntouch .vitepress\u002Ftheme\u002Fuser\u002Fapi.ts\n```\n\nThen, we can write the code to fetch the user data and to logout the user in the `.vitepress\u002Ftheme\u002Fuser\u002Fapi.ts` file:\n\n```ts [.vitepress\u002Ftheme\u002Fuser\u002Fapi.ts]\nexport const fetchUser = () => api('api\u002Fuser')\n\nexport const postLogoutUser = () => api('logout', { method: 'POST' })\n```\n\nThese functions abstract the raw API calls. The rest of the feature can use the explicit names `fetchUser` and `postLogoutUser` without knowing the request details.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nHow do I name API functions? I use the `fetch` prefix for queries, followed by the resource name. For mutations, I use the HTTP verb followed by the resource name. This makes the functions easy to recognize and remember.\n::\n\nNow, we can create the query used to fetch the user data:\n\n```ts [.vitepress\u002Ftheme\u002Fuser\u002Fqueries\u002Fusers.ts]\nimport type { User } from '@\u002Fuser\u002Ftypes\u002Fuser'\n\nexport const useUser = defineQuery(() => {\n  return useQuery\u003CUser>({\n    key: ['user'],\n    query: () => fetchUser().then(response => response.data),\n    enabled: typeof document !== 'undefined',\n  })\n})\n```\n\nWe also need to define a new type for the user:\n\n```ts [.vitepress\u002Ftheme\u002Fuser\u002Ftypes\u002Fuser.ts]\nexport interface User {\n  id: number\n  name: string\n  username: string\n  avatar: string\n}\n```\n\nHere is how the query works:\n\n- `defineQuery` defines a reusable query within the Vue context.\n- `useQuery` describes the key, request function, and state returned to components.\n- `key` identifies the query in Pinia Colada's cache. When `useUser` is called again, Pinia Colada can reuse a fresh cached result instead of sending another request.\n- `query` returns the promise for the API request. We return the response's `data` property because Laravel resources wrap their payload in `data`.\n- `enabled` limits the request to the browser. We do not want to call the API while VitePress is generating the site.\n\nWe can now call `useUser` anywhere in the application. Components do not need to await the request; they consume its reactive state and let Vue update the interface when the data arrives.\n\nPinia Colada also deduplicates requests, refetches stale data when needed, exposes the cache, and provides hooks for optimistic updates.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nDeduplication matters because multiple components can call `useUser` on the same page. Pinia Colada makes one API request and shares the result between those calls.\n::\n\nThen, we can write the mutation to logout the user:\n\n```ts [.vitepress\u002Ftheme\u002Fuser\u002Fmutations\u002Fusers.ts]\nimport type { User } from '@\u002Fuser\u002Ftypes\u002Fuser'\n\nexport const useLogoutUser = defineMutation(() => {\n  const queryCache = useQueryCache()\n\n  return useMutation({\n    mutation: () => postLogoutUser(),\n\n    onMutate: () => {\n      const oldUser = queryCache.getQueryData\u003CUser>(['user'])\n\n      queryCache.setQueryData(['user'], null)\n      queryCache.cancelQueries({ key: ['user'], exact: true })\n\n      return { oldUser }\n    },\n    onError: (_, __, { oldUser }) => {\n      if (oldUser) {\n        queryCache.setQueryData(['user'], oldUser)\n      }\n    },\n    onSettled: () =>\n      queryCache.invalidateQueries({ key: ['user'], exact: true }),\n  })\n})\n```\n\nThis mutation uses an optimistic update. When the user clicks logout, `onMutate` removes the user from the cache immediately, so the interface swaps the logout button for the login button without waiting for the server. It returns the previous user so `onError` can restore it if the request fails. `onSettled` runs in either case and invalidates the user query, allowing Pinia Colada to refresh it when it is used again.\n\nUpdate the header to call `useUser` and display the appropriate button:\n\n```vue [.vitepress\u002Ftheme\u002Fcommon\u002Fcomponents\u002FTheHeader.vue]\n\u003Cscript lang=\"ts\" setup>\nconst { state } = useUser()\n\u003C\u002Fscript>\n\n\u003Ctemplate>\n  \u003Cheader>\n    \u003Cdiv>\n      \u003C!-- ... -->\n      \u003Cdiv>\n        \u003C!-- ... -->\n        \u003CButton v-if=\"state.data\" label=\"Logout\" \u002F>\n        \u003CButton v-else :href=\"loginUrl\" label=\"Login\" \u002F>\n      \u003C\u002Fdiv>\n    \u003C\u002Fdiv>\n  \u003C\u002Fheader>\n\u003C\u002Ftemplate>\n```\n\nThen, we can add our mutation:\n\n```vue [Example]\n\u003Cscript lang=\"ts\" setup>\nconst { mutate: logout } = useLogoutUser()\n\u003C\u002Fscript>\n\n\u003Ctemplate>\n  \u003Cheader>\n    \u003Cdiv>\n      \u003C!-- ... -->\n      \u003Cdiv>\n        \u003C!-- ... -->\n        \u003CButton v-if=\"state.data\" label=\"Logout\" @click=\"logout\" \u002F> \u003C!-- [!code ++] -->\n      \u003C\u002Fdiv>\n    \u003C\u002Fdiv>\n  \u003C\u002Fheader>\n\u003C\u002Ftemplate>\n```\n\nTry it now, but the logout action will not work yet. Our `Button` component is currently only a link:\n\n```vue [.vitepress\u002Ftheme\u002Fcommon\u002Fcomponents\u002FButton.vue]\n\u003Ctemplate>\n  \u003Ca :href :class=\"ui\">\n    {{ props.label }}\n  \u003C\u002Fa>\n\u003C\u002Ftemplate>\n```\n\nWe need a component that renders an anchor when it receives `href` and a button when it receives `onClick`. Vue's built-in [`component`](https:\u002F\u002Fvuejs.org\u002Fapi\u002Fbuilt-in-special-elements#component) element makes this possible.\n\nFirst, allow the props to accept `onClick`:\n\n```ts [Example]\nexport interface ButtonProps {\n  href?: string \u002F\u002F [!code highlight]\n  label: string\n  color?: ButtonVariants['color']\n  class?: any\n  onClick?: () => void \u002F\u002F [!code ++]\n}\n```\n\nThen, we can use the built-in special component `component`:\n\n```vue [Example]\n\u003Ctemplate>\n  \u003Ccomponent\n    :is=\"props.href ? 'a' : 'button'\"\n    :href=\"props.href\"\n    :class=\"ui\"\n    @click=\"props.onClick\"\n  >\n    {{ props.label }}\n  \u003C\u002Fcomponent>\n\u003C\u002Ftemplate>\n```\n\nThe important line is `:is=\"props.href ? 'a' : 'button'`: it chooses an anchor or a button based on the props.\n\nNow the complete flow works:\n\n1. Users can log in using GitHub\n2. Users can log out smoothly from the frontend\n3. Users can log in again\n\n## Conclusion\n\nAuthentication is now a reusable frontend feature. The application can fetch the current user, share the cached result across components, and update the interface optimistically when the user logs out.\n\nThis gives the comment system everything it needs to know whether someone is signed in and which controls to display. In the final article, we will use the same feature-based Pinia Colada structure to list, create, edit, and delete comments.\n",{"title":5,"description":3266},"empower-and-dynamize-our-vitepress-blog-with-a-laravel-api",{"loc":3270},"series\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fstreamlining-user-authentication-from-frontend-to-backend","G0K0WXVUJOXzotEsfphTEtNZtVwaC_-MKPjELUx7ZU4",{"overview":3278,"chapters":3452},{"id":3279,"title":3280,"body":3281,"contentId":3436,"date":3437,"description":3438,"extension":3267,"github":3268,"meetTheInstructor":3439,"meta":3440,"navigation":86,"part":3268,"path":3441,"rawbody":3442,"robots":3268,"schemaOrg":3268,"seo":3443,"seriesSlug":3273,"sitemap":3444,"stem":3445,"subtitle":3446,"topics":3447,"__hash__":3451},"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":3282,"toc":3433},[3283,3286,3289,3292,3296,3305,3308,3317,3320,3323,3404,3407,3410,3413,3423,3427],[10,3284,3285],{},"Hello! 👋",[10,3287,3288],{},"After building our VitePress blog, we are ready to make it more dynamic with a Laravel API.",[10,3290,3291],{},"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.",[3293,3294],"callout-read-more",{"id":3295},"43c95b33-041c-4108-ab98-0d21ef60ed7f",[10,3297,3298,3299,3304],{},"This series introduces back-end development by creating a ",[20,3300,3303],{"href":3301,"rel":3302},"https:\u002F\u002Flaravel.com",[24],"Laravel"," API that gives our blog a few interactive features.",[10,3306,3307],{},"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,3309,3310,3311,3316],{},"Although the focus is on the back end, we will also integrate the API into our VitePress blog. We will use Vue.js and ",[20,3312,3315],{"href":3313,"rel":3314},"https:\u002F\u002Fpinia-colada.esm.dev\u002F",[24],"Pinia Colada"," as our data-fetching framework. VitePress is a Vue.js application, so we can extend it with the components we need.",[10,3318,3319],{},"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,3321,3322],{},"Throughout the series, we will build a Laravel API and integrate it with our VitePress blog. We will cover:",[922,3324,3325,3332,3359,3370,3376,3386,3392,3398],{},[39,3326,3327,3331],{},[3328,3329,3330],"strong",{},"Setting up the Laravel project",": Create a new Laravel project and become familiar with its structure.",[39,3333,3334,3337,3338,351,3343,351,3348,355,3353,3358],{},[3328,3335,3336],{},"Improving the development workflow",": Configure ",[20,3339,3342],{"href":3340,"rel":3341},"https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fpint",[24],"Pint",[20,3344,3347],{"href":3345,"rel":3346},"https:\u002F\u002Fgithub.com\u002Frectorphp\u002Frector",[24],"Rector",[20,3349,3352],{"href":3350,"rel":3351},"https:\u002F\u002Fgithub.com\u002Flarastan\u002Flarastan",[24],"Larastan",[20,3354,3357],{"href":3355,"rel":3356},"https:\u002F\u002Fpestphp.com\u002F",[24],"Pest"," for formatting, refactoring, static analysis, and testing.",[39,3360,3361,3364,3365,1193],{},[3328,3362,3363],{},"Adding social authentication",": Let users sign in with GitHub through ",[20,3366,3369],{"href":3367,"rel":3368},"https:\u002F\u002Flaravel.com\u002Fdocs\u002F11.x\u002Fsocialite",[24],"Laravel Socialite",[39,3371,3372,3375],{},[3328,3373,3374],{},"Connecting the applications",": Configure Sanctum, CORS, CSRF protection, and the first requests between the VitePress frontend and the Laravel API.",[39,3377,3378,3381,3382,3385],{},[3328,3379,3380],{},"Managing authentication state",": Use ",[20,3383,3315],{"href":3313,"rel":3384},[24]," to retrieve the current user and log out with an optimistic update.",[39,3387,3388,3391],{},[3328,3389,3390],{},"Building the comment API",": Create the models, relationships, endpoints, validation, authorization, and tests for comments.",[39,3393,3394,3397],{},[3328,3395,3396],{},"Keeping the backend in sync",": Generate post metadata from VitePress and synchronize it with the Laravel database.",[39,3399,3400,3403],{},[3328,3401,3402],{},"Building the comment interface",": Fetch, create, edit, and delete comments from the VitePress frontend.",[10,3405,3406],{},"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,3408,3409],{},"Testing is part of the development process and will be included at each stage, so it does not need a dedicated article.",[10,3411,3412],{},"If you have questions, feedback, or suggestions, feel free to share them in the comments. Your input helps improve the series.",[644,3414,3415],{"color":646,"icon":647},[10,3416,3417,3418,3422],{},"This series assumes prior knowledge of TypeScript, Vue.js, and Laravel. If you are unfamiliar with any of these technologies, review the ",[20,3419,3421],{"href":3420},"\u002Fseries\u002Fcreate-a-blog-with-vitepress-and-vue-js-from-scratch","Create a Blog with VitePress and Vue.js from Scratch"," first.",[28,3424,3426],{"id":3425},"chapters","Chapters",[3428,3429],"series-chapters-list",{"className":3430},[3431,3432],"mx-auto","max-w-5xl",{"title":70,"searchDepth":83,"depth":83,"links":3434},[3435],{"id":3425,"depth":83,"text":3426},"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":3280,"description":3438},{"loc":3441},"series\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api","Transform your VitePress blog into a dynamic platform with an API",[3448,3449,3450],"laravel","vitepress","api","JLBtX9BKfN72BkhcYisEXraNGTvZSnT5YHM05A_uemk",[3453,3458,3463,3468,3473,3478,3483,3484],{"contentId":3454,"title":3455,"description":3456,"path":3457,"part":77,"github":3268,"topics":3268},"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":3459,"title":3460,"description":3461,"path":3462,"part":83,"github":3268,"topics":3268},"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":3464,"title":3465,"description":3466,"path":3467,"part":90,"github":3268,"topics":3268},"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":3469,"title":3470,"description":3471,"path":3472,"part":96,"github":3268,"topics":3268},"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":3474,"title":3475,"description":3476,"path":3477,"part":101,"github":3268,"topics":3268},"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":3479,"title":3480,"description":3481,"path":3482,"part":107,"github":3268,"topics":3268},"e6040e0a-4997-40d6-bde8-332cbca0f307","Bridging the Gap: Connecting Your Frontend and Backend","Connect a VitePress frontend to a Laravel API with Sanctum, CORS, CSRF protection, shared credentials, and a reusable API client.","\u002Fseries\u002Fempower-and-dynamize-our-vitepress-blog-with-a-laravel-api\u002Fbridging-the-gap-connecting-your-frontend-and-backend",{"contentId":3264,"title":5,"description":3266,"path":3270,"part":112,"github":3268,"topics":3268},{"contentId":3485,"title":3486,"description":3487,"path":3488,"part":118,"github":3268,"topics":3268},"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",1795016694076]