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
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: 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_onlyand the rate is inestimated_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,
missinglists 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.