Docs
Authentication
Protected API Routes

Protecting API Routes with Supabase

This document provides an overview of how to protect API routes in your StartupBolt project using Supabase authentication. By following this guide, you can ensure that only authenticated users can access certain API endpoints.

Example Implementation

Here is an example of how to 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.

Code Example

import { NextResponse } from 'next/server';
import { createClient } from '@/utils/supabase/server';
 
export async function POST(request) {
    try {
        const supabase = createClient();
 
        const { data: { user }, error } = await supabase.auth.getUser();
 
        // Users who are not logged in can't make a purchase
        if (error || !user) {
            return NextResponse.json({ error: "Please login to continue." }, { status: 401 });
        }
 
        // 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

  1. Import Supabase Client

    Import the createClient function from the server-side Supabase client:

    import { createClient } from '@/utils/supabase/server';
  2. Initialize Supabase Client

    Inside the POST function, initialize the Supabase client:

    const supabase = createClient();
  3. Retrieve User Information

    Use the Supabase client to get the authenticated user's information:

    const { data: { user }, error } = await supabase.auth.getUser();
  4. Check Authentication Status

    Check if there was an error retrieving the user or if the user is not authenticated. If so, return a 401 status with an error message:

    if (error || !user) {
        return NextResponse.json({ error: "Please login to continue." }, { status: 401 });
    }
  5. Handle the Request

    If the user is authenticated, proceed with handling the request. Replace the placeholder comment with your actual business logic, such as processing a purchase or updating the database:

    // Your business logic here
    // Example: Process a purchase, update the database, etc.
  6. Return a Success Response

    After successfully handling the request, return a success response:

    return NextResponse.json({ message: "Request processed successfully." });
  7. Error Handling

    Catch any errors that occur during the process and return a 500 status with the error message:

    catch (error) {
        return NextResponse.json({ error: error.message }, { status: 500 });
    }

Summary

By following the above steps, you can protect your API routes to ensure that only authenticated users can access them. This helps enhance the security of your application and provides a better user experience by preventing unauthorized access.

For more detailed information on Supabase and its authentication capabilities, refer to the Supabase documentation (opens in a new tab).