# How to extract recipes from TikTok and Instagram links in Node.js

To extract a recipe from a TikTok or Instagram post in Node.js, send the
post's link to the ClipParse API. It returns the recipe as JSON: the title,
ingredients with quantities and units, ordered steps, timings and servings.

You need a ClipParse API key: get a free one at
[clipparse.com/get-free-key](https://clipparse.com/get-free-key). It takes
seconds and doesn't require a credit card.

Building an iOS or Android app? The
[iOS](/guides/import-recipes-from-tiktok-instagram-ios) and
[Android](/guides/import-recipes-from-tiktok-instagram-android) SDKs are the
recommended way to call the API from a mobile app: extraction is more
reliable through them.

## Requirements

- Node.js 18 or later, for the built-in `fetch`. No package is needed.
- A ClipParse API key, in the `CLIPPARSE_API_KEY` environment variable

## Extract a recipe from a link

Send the link to `POST https://api.clipparse.com/v1/extract`, with your key
in the `X-API-Key` header:

```js
const API_URL = "https://api.clipparse.com/v1/extract";

export class ClipParseError extends Error {
  constructor(status, code, message, retryAfter) {
    super(message ?? `HTTP ${status}: ${code}`);
    this.name = "ClipParseError";
    this.status = status;
    this.code = code;
    this.retryAfter = retryAfter;
  }

  get retryable() {
    return this.status >= 500 || this.code === "rate_limited";
  }
}

export async function extractRecipe(postUrl) {
  const response = await fetch(API_URL, {
    method: "POST",
    headers: {
      "X-API-Key": process.env.CLIPPARSE_API_KEY,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ url: postUrl }),
    signal: AbortSignal.timeout(60_000),
  });
  const body = await response.json().catch(() => ({}));
  if (response.ok && (body.status === "success" || body.status === "no_recipe")) {
    return body;
  }
  const retryAfter = response.headers.get("Retry-After");
  throw new ClipParseError(
    response.status,
    body.code ?? (response.status === 422 ? "invalid_request" : "unexpected_response"),
    body.message,
    retryAfter ? Number(retryAfter) : undefined,
  );
}
```

The response's `status` says what happened. On `success`, the body carries
the `recipe`. On `no_recipe`, the post holds no usable recipe, and `code`
says why: `no_recipe_found`, or `multiple_recipes_detected` when it holds
several recipes in one post. Both come with HTTP 200: a post with no recipe
is an expected outcome, not an error.

```js
const result = await extractRecipe("https://www.tiktok.com/@somecreator/video/1234567890");
if (result.status === "success") {
  const { recipe } = result;
  console.log(recipe.title);
  for (const ingredient of recipe.ingredients) {
    console.log(ingredient.raw);
  }
  for (const step of recipe.steps) {
    console.log(step.text);
  }
} else {
  console.log("No recipe:", result.code);
}
```

## Handle errors

Every other outcome is an error with a `code`, thrown above as a
`ClipParseError`:

- `platform_unsupported` (400): the link isn't a TikTok or Instagram post.
- `post_unavailable` (404): the post was deleted, is private, or doesn't
  exist. Retrying won't help.
- `unauthorized` or `invalid_key` (401), `key_revoked` (403): a problem with
  your API key.
- `rate_limited` (429): too many requests in a short time. Retry after the
  number of seconds in the `Retry-After` header.
- `quota_exceeded` (429): the key's allowance is spent until the time in
  `resetsAt`.
- `internal_error` (500): a transient failure. Retry with backoff.

A value that isn't a URL gets a 422 with a validation error, which
`extractRecipe` reports as `invalid_request`.

To show a message to your users, map the codes they can act on and treat the
rest as a generic failure:

```js
const USER_MESSAGES = {
  platform_unsupported: "Only TikTok and Instagram links are supported.",
  invalid_request: "That doesn't look like a link.",
  post_unavailable: "This post was deleted, is private, or doesn't exist.",
  rate_limited: "Too many imports right now. Try again later.",
  quota_exceeded: "Too many imports right now. Try again later.",
};

export function userMessage(error) {
  return USER_MESSAGES[error.code] ?? "Something went wrong. Please try again.";
}
```

The API key errors are yours to fix, not the user's: log them, with their
`message`, so you notice. Branch on `code`, not on `message`: its wording
can change.

## Retry what's worth retrying

Only `internal_error` and `rate_limited` are worth retrying. This wrapper
retries them a few times, waiting for `Retry-After` when the API gives one
and backing off otherwise:

```js
export async function extractWithRetry(postUrl, attempts = 3) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await extractRecipe(postUrl);
    } catch (error) {
      const wait = error.retryAfter ?? 2 ** attempt;
      if (!(error instanceof ClipParseError) || !error.retryable || attempt === attempts || wait > 60) {
        throw error;
      }
      await new Promise((resolve) => setTimeout(resolve, wait * 1000));
    }
  }
}
```

## Use the recipe's fields

The recipe's fields:

- `title`, and `language`: a short code such as `"en"`.
- `sourceUrl`: the post the recipe came from.
- `thumbnailUrl`: the post's thumbnail, when there is one. The URL expires,
  so download the image if you keep the recipe.
- `servings`, `prepTimeMinutes` and `cookTimeMinutes`, when the post states
  them.
- `ingredients`, in the order the post lists them. Each has a `name`, a
  `quantity` and a `unit`, the `prep` note (such as "finely chopped"), the
  `section` it belongs to (such as "For the sauce"), and `raw`: the line
  exactly as the post wrote it.
- `steps`, in order. Each has its `text`, a `durationMinutes` when stated,
  and a `section`.

Anything the post doesn't state is `null`. For a range such as "2-3 tbsp",
`quantity` is the midpoint and `quantityMin` and `quantityMax` hold the ends.
`unit` is one of `g`, `kg`, `ml`, `l`, `tsp`, `tbsp`, `cup`, `pt`, `qt`,
`gal`, `oz`, `lb`, `pinch` or `each`. `each` means the ingredient is
counted, such as 3 eggs; `null` means the post gives no unit.

To show an amount, use the range when there is one:

```js
export function amountText(ingredient) {
  if (ingredient.quantity === null) {
    return null;
  }
  const amount =
    ingredient.quantityMin !== null && ingredient.quantityMax !== null
      ? `${ingredient.quantityMin}–${ingredient.quantityMax}`
      : `${ingredient.quantity}`;
  return ingredient.unit === null || ingredient.unit === "each" ? amount : `${amount} ${ingredient.unit}`;
}
```

For TypeScript, generate the types from the OpenAPI spec at
[docs.clipparse.com/openapi.json](https://docs.clipparse.com/openapi.json).

## Track your allowance

Every response to a request with a valid key reports your allowance in
headers: `X-Quota-Limit`, `X-Quota-Used`, `X-Quota-Remaining`, and
`X-Quota-Reset`, the time it renews. `X-Credits-Used` says what the request
itself used. Errors and `no_recipe` outcomes use no credits.

Every response also carries an `X-Request-Id`. Log it with failures, and
quote it when contacting support.

## Get schema.org JSON-LD instead

If your app already imports recipes in the schema.org format, call
`POST https://api.clipparse.com/v1/extract/schema-org` with the same request
instead. On success, the body is a `schema.org/Recipe` object served as
`application/ld+json`. The other outcomes are unchanged, so tell them apart
by the `Content-Type`.

## Next steps

- The [API reference](https://docs.clipparse.com/) lists every field and
  outcome.
- The [Python guide](/guides/extract-recipes-from-tiktok-instagram-python)
  shows the same calls in Python.
- [Pricing](https://clipparse.com/pricing) covers what each extraction costs
  and the plans past the free tier.
