API Routes
Creating Public, Protected, and Paid API Endpoints
Next.js API Routes allow you to create backend endpoints directly within your Next.js application. Any file named route.ts
(or route.js
) inside the /app/api
directory structure becomes an API endpoint.
StarterKitPro utilizes NextAuth.js(Authjs) for handling authentication seamlessly via secure cookies.
API Client Helper
StarterKitPro includes an apiClient
helper (lib/api.ts
) built on Axios.
It's recommended for frontend API calls as it automatically: - Sets the base
URL to /api
. - Redirects to the login page on 401 Unauthorized
errors. -
Redirects to the billing page on 403 Forbidden
errors (for paid routes). -
Displays other API errors using toast notifications.
Creating API Routes
Here's how to structure different types of API routes:
1. Public API Route
These routes are accessible to anyone, without requiring authentication.
Example Backend:
Example Frontend Call:
2. Protected API Route (Authentication Required)
These routes require the user to be signed in.
Automatic Session Handling
NextAuth.js handles session management via secure HTTP-only cookies. This means you don't need to manually pass authentication tokens from the frontend when using the apiClient
or standard browser fetch requests, as the browser automatically includes the cookie.
Example Backend:
Example Frontend Call:
3. Paid API Route (Authentication + Access Required)
These routes require the user to be signed in AND have active access (e.g., a subscription or one-time purchase).
Checking Access Efficiently
The backend example checks user.hasAccess
from the curret user. Because we hasAccess to true in webhook.
Example Backend:
Example Frontend Call:
Remember to adapt the database models (prisma/schema.prisma
) and access checks (hasAccess
field) based on your specific payment provider integration (Stripe or Lemon Squeezy) and how you manage user entitlements via webhooks.