What You’ll Build
A Next.js application that:- Uses a proxy API route to forward Decart API requests
- Keeps your API key secure on the server
- Enables client-side SDK usage with zero code changes
- Provides a simple image generation demo
Architecture
/api/decart, which Next.js forwards to Decart’s API with your server-side API key attached.
Prerequisites
- Node.js 18 or higher
- A Decart API key
Setup
Configure your API key
Create a
.env.local file:Use
.env.local in Next.js to keep environment variables secure and server-side only.Start the development server
Proxy API Route
Theapp/api/decart/[...path]/route.ts file sets up the proxy:
route() function creates GET and POST handlers that:
- Read your API key from
process.env.DECART_API_KEY - Forward all requests to
api.decart.ai - Return responses back to the client
Client Page Component
Theapp/page.tsx component uses the SDK with the proxy:
Key Concepts
Proxy Route Constant
ThePROXY_ROUTE constant provides the default proxy path:
Catch-All Route
The[...path] directory name creates a catch-all route that matches:
/api/decart/v1/process/api/decart/v1/queue/submit/api/decart/v1/realtime/connect- And all other Decart API endpoints
Environment Variables
Next.js keeps.env.local variables server-side only:
process.env.DECART_API_KEY.
Client Component
Mark components that use hooks with"use client":
Custom Configuration
Custom API Key Source
Pass a custom API key:Custom Proxy Path
Create proxy at a different path:Advanced Usage
Adding Authentication
Wrap the route with authentication:Rate Limiting
Implement rate limiting:Logging Requests
Real-time API Usage
The proxy also works with the real-time API:Deployment
Vercel
Set environment variables in the Vercel dashboard:Other Platforms
SetDECART_API_KEY in your platform’s environment configuration.
Production Best Practices
- Use
.env.local- Never commit API keys to git - Add Authentication - Protect your proxy from unauthorized use
- Implement Rate Limiting - Prevent abuse and control costs
- Add Monitoring - Track usage and errors
- Enable CORS - Configure allowed origins in production
- Use HTTPS - Always use secure connections
Troubleshooting
API Key Not Found
Ensure.env.local exists and contains: