Integrations · Web application

US import duty in a Next.js app, with the key on the server

A form and a route handler that call the TariffTrust API: the browser only ever calls your route, never the API with your key.

A Next.js app can show US import duties to its users without ever exposing your key: a form in the browser posts to a route handler of your app, and the route handler calls the TariffTrust API with the official client, on the server.

Run the example

Terminal
npm install
TARIFFTRUST_API_KEY=tarifftrust_... npm run dev

Then open the app on your machine, at port 3000: the form takes an HTS code, a country of origin and an optional value.

The route handler

app/api/duty/route.ts
// app/api/duty/route.ts: the API key stays on the server.
import { NextResponse } from "next/server";
import { InvalidInputError, TariffTrust } from "tarifftrust";

const client = new TariffTrust();

export async function POST(request: Request) {
  const { hts, origin, customs_value } = await request.json();
  if (!hts || !origin) {
    return NextResponse.json({ error: "An HTS code and an origin are required" }, { status: 400 });
  }
  try {
    const result = await client.estimate({ hts, origin, customs_value: customs_value || null });
    return NextResponse.json({
      status: result.status,
      duty: result.estimated_duty,
      lines: (result.duties ?? []).map(({ name, amount }) => ({ name, amount })),
      missing: (result.missing ?? []).map(({ question }) => question),
    });
  } catch (error) {
    if (error instanceof InvalidInputError) {
      return NextResponse.json({ error: error.message, fields: error.fields }, { status: 422 });
    }
    return NextResponse.json({ error: "Duties are not available right now" }, { status: 502 });
  }
}

What to keep in mind

  • Keep the key on the server: never import the client into a client component, and never give the key a NEXT_PUBLIC_ name: Next.js writes those variables into the JavaScript it sends to the browser.
  • The value is optional. Without it, the answer gives an amount only where the duty does not depend on the value; otherwise its status is rate_only and the rate is in estimated_duty_rate, which this route does not pass on.
  • Missing information is a question, not an error. When the duty depends on a detail of the goods, missing lists the questions to ask your user.

The whole example

The complete, runnable example is in the public repository of the official clients, under the MIT license. The API reference describes every field of the request and of the answer, the errors and how to retry safely, and the integration guides how to read an answer and estimate a declaration.

Get an API key

The API and the MCP server come with the plans that include them (Pro). Each estimate counts once in the plan's monthly quota; a retry with the same Idempotency-Key, or an answer that only asks for missing information, does not count.