ESC
NuxtStarterAI logo
Menu
On this page

Tutorials > Protected API Calls

Proceed to the /server/api folder – name a file such as hello.ts is your API endpoint(http://YOUR_DOMAIN_HERE/api/hello)! ✨ ✨ For an extra bit of simplicity, go to the /libs/api.ts helper file (it's like an axios wizard with interceptors).


1. Automatic error messages for common cases such as Please Login , You need to be on paid plan to use this feature etc.


2. Redirecting user to the login page upon 401 error


🍪 Supabase provides authentication support using cookies – it's fully automatic! 🚀 Simply make a standard API call on the front-end:


/app/components/any-component.vue
1<template> 2 <div> 3 ... 4 <button @click="makeProtectedHttpCall"></button> 5 ... 6 </div> 7</template> 8 9<script lang="tsx" setup> 10import { useAuthStore } from '@/store/useAuthStore'; 11import apiClient from "@/libs/api"; 12import config from "@/config"; 13 14 15const supabase = useSupabaseClient() 16 17const isLoading = ref<boolean>(false); 18 19const store = useAuthStore(); 20const { user } = storeToRefs(store) 21 22const makeProtectedHttpCall = async () => { 23 isLoading.value = true; 24 25 if (user) { 26 await apiClient.post("/api/protected-api"); 27 } 28 29 isLoading.value = false; 30}; 31</script>

🔙 On the backend, we grab the session magic and use it to fetch the user from the database. But first things first – configure that database! 🛠️ Your API file is the secret sauce and should have a vibe like this:


/server/api/protected-api.ts
1import { serverSupabaseUser } from '#supabase/server'; 2 3 export default defineEventHandler(async (event) => { 4 try { 5 const user = await serverSupabaseUser(event) 6 7 // User who are not logged in can't make a purchase 8 if (!user) { 9 throw createError({ statusCode: 401, statusMessage: "You must be logged in to make a purchase." }); 10 } 11 12 // you can do what you need to do with the authenticated user 13 } catch (error) { 14 console.error(error); 15 throw error; 16 } 17 });