This is a Next.js template project that's preconfigured to work with Replicate's API.
It uses Next's newer App Router and Server Components.
You can use this as a quick jumping-off point to build a web app using Replicate's API, or you can recreate this codebase from scratch by following the guide at replicate.com/docs/get-started/nextjs
- app/page.js - React frontend that renders the home page in the browser
- app/api/predictions/route.js - API endpoint that calls Replicate's API to create a prediction
- app/api/predictions/[id]/route.js - API endpoint that calls Replicate's API to get the prediction result
- app/api/webhooks/route.js - API endpoint that receives and validates webhooks from Replicate
Install dependencies:
npm install
Create a git-ignored text file for storing secrets like your API token:
cp .env.example .env.local
Add your Replicate API token to .env.local
:
REPLICATE_API_TOKEN=<your-token-here>
Run the development server:
npm run dev
Open http://localhost:3000 with your browser.
For detailed instructions on how to create and use this template, see replicate.com/docs/get-started/nextjs
Webhooks provide real-time updates about your predictions. When you create a prediction or training, specify a URL that you control and Replicate will send HTTP POST requests to that URL when the prediction is created, updated, and completed.
This app is set up to optionally request, receive, and validate webhooks.
- You specify a webhook URL when creating a prediction in app/api/predictions/[id]/route.js
- Replicate sends POST requests to the handler in app/api/webhooks/route.js as the prediction is updated.
To test webhooks in development, you'll need to create a secure tunnel to your local machine, so Replicate can send POST requests to it. Follow these steps:
- Download and set up
ngrok
, an open-source tool that creates a secure tunnel to your local machine so you can receive webhooks. - Run ngrok to create a publicly accessible URL to your local machine:
ngrok http 3000
- Copy the resulting ngrok.app URL and paste it into
.env.local
, like this:NGROK_HOST="https://020228d056d0.ngrok.app"
. - Leave ngrok running.
- In a separate terminal window, run the app with
npm run dev
- Open localhost:3000 in your browser and enter a prompt to generate an image.
- Go to replicate.com/webhooks to see your prediction status.
Follow these steps to set up your development environment to validate incoming webhooks:
- Get your signing secret by running:
curl -s -X GET -H "Authorization: Bearer $REPLICATE_API_TOKEN" https://api.replicate.com/v1/webhooks/default/secret
- Add this secret to
.env.local
, like this:REPLICATE_WEBHOOK_SIGNING_SECRET=whsec_...
- Now when you run a prediction, the webhook handler in app/api/webhooks/route.js will verify the webhook.