Back to APIs

Automate posting media and manage social interactions.

Using the Instagram API with Trigger.dev

You can use Trigger.dev with any existing Node SDK or even just using fetch. Using io.runTask makes your Instagram background job resumable and appear in our dashboard.

Use io.runTask() and the official SDK or fetch.

Use our HTTP endpoint to subscribe to webhooks

Example code using Instagram

Below are some working code examples of how you can use Instagram with Trigger.dev. These samples are open source and maintained by the community, you can copy and paste them into your own projects.

1
import { TriggerClient, eventTrigger } from "@trigger.dev/sdk";
2
import z from "zod";
3
4
// You need a professional Instagram account that is connected with your facebook business account
5
// Get started from here: https://developers.facebook.com/docs/instagram-api/getting-started
6
// For permanent token you have to create system user: https://business.facebook.com/settings/system-users
7
// You can find your instagram user id from here: https://business.facebook.com/settings/instagram-account-v2s
8
const token = {
9
userId: process.env.INSTAGRAM_USER_ID!,
10
accessToken: process.env.FACEBOOK_ACCESS_TOKEN!,
11
};
12
const endpointURLCreate = `https://graph.facebook.com/v18.0/${token.userId}/media`;
13
const endpointURLPublish = `https://graph.facebook.com/v18.0/${token.userId}/media_publish`;
14
15
client.defineJob({
16
id: "post-instagram",
17
name: "Post on Instagram",
18
version: "1.0.0",
19
trigger: eventTrigger({
20
name: "post-instagram",
21
schema: z.object({
22
caption: z.string().max(2200), // instagram captions are limited to 2200 characters
23
imageUrl: z.string(),
24
}),
25
}),
26
run: async (payload, io, ctx) => {
27
// wrap the SDK call in io.runTask for resumability and log display
28
await io.runTask(
29
"Post on Instagram",
30
async () => {
31
// Publishing a single media post is a two step process,
32
// Step 1: Create container
33
const createContainerUrl = `${endpointURLCreate}?image_url=${
34
payload.imageUrl
35
}&caption=${encodeURIComponent(payload.caption)}&access_token=${
36
token.accessToken
37
}`;
38
39
const containerResponse = await fetch(createContainerUrl, {
40
method: "POST",
41
}).then((response) => response.json());
42
43
// Extract container ID
44
const containerId = containerResponse.id;
45
46
// Step 2: Publish container
47
const publishContainerUrl = `${endpointURLPublish}?creation_id=${containerId}&access_token=${token.accessToken}`;
48
49
const publishResponse = await fetch(publishContainerUrl, {
50
method: "POST",
51
}).then((response) => response.json());
52
53
return publishResponse;
54
},
55
56
// Add metadata to the task to improve the display in the logs
57
{ name: "Post to Instagram", icon: "instagram" }
58
);
59
},
60
});