Protecting API Routes with Supabase
API route protection is essential to secure your application and ensure sensitive operations are only accessible to authorized users. With Supabase authentication, you can easily implement robust protection for your API routes.
In this guide, you'll learn how to:
- Authenticate users before granting access to API routes.
- Ensure users have active plans or sufficient credits to access premium features.
Example Implementation
Here's how you can protect an API route in your project. This example uses the createClient
utility function to interact with Supabase and check the user's authentication status.
To learn more about setting up Supabase client, refer to the Supabase Client Setup and Usage Guide.
Protecting API Routes for Authenticated Users
import { NextResponse } from 'next/server';
import { createClient } from '@/utils/supabase/server';
export async function POST(request) {
try {
const supabase = createClient();
// Check user authentication
const { data: { user }, error } = await supabase.auth.getUser();
// Deny access to unauthenticated users
if (error || !user) {
return NextResponse.json({ error: "Please login to continue." }, { status: 401 });
}
// Add your business logic here
// Example: Process a purchase, update the database, etc.
return NextResponse.json({ message: "Request processed successfully." });
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
Explanation
- Authentication Check: Ensure only logged-in users can access the route.
- Error Handling: Return appropriate error responses for unauthenticated users or unexpected failures.
- Business Logic: Replace the placeholder business logic with your functionality, such as processing payments or updating the database.
Extending Protection: Authenticated Users with Active Plans
To ensure users have active plans, validate their credit balance after authentication.
const { data: userData, error: userError } = await supabase
.from('customers')
.select('credits')
.eq('id', user.id)
.single();
if (userError || !userData || userData.credits <= 0) {
return NextResponse.json({ error: "Insufficient credits. Please purchase more credits to continue." }, { status: 403 });
}
Summary
Now you know how to protect API routes in your StartupBolt project using Supabase authentication. Whether you're securing basic routes or implementing advanced access control, these steps help you ensure only authorized users and those with active plans can access your API.
For more details, refer to: