Build your shipping company website
This tutorial shows how to build a shipping company website on the API: a tracking page, a price calculator, a coverage checker, a "ship now" order form with address validation, a merchant login area and live status updates. It maps each page to the API calls behind it and includes a small but real server that keeps the key safe.
The one rule that shapes everything: the API key and secret live on your server, never in the browser. The browser talks to your website's server; your server talks to the LastMile API.
| Page of your site | Calls from your server | Scopes |
|---|---|---|
| Tracking page | GET /shipments/{trackingNumber} (to verify the visitor), then GET /shipments/{trackingNumber}/tracking |
shipments:read |
| Price calculator | GET /geography/coverage/cities, GET /geography/districts, POST /pricing/quote |
geography:read, pricing:read |
| Coverage checker | GET /geography/coverage |
geography:read |
| "Ship now" order form | GET /geography/resolve, POST /pricing/quote, POST /shipments, GET /shipments/{trackingNumber}/label |
geography:read, pricing:read, shipments:write, shipments:read |
| Merchant login area | POST /auth/login, POST /auth/refresh, then GET /shipments, POST /shipments with the merchant's token |
The merchant login's own permissions |
| Status updates | Webhooks into your server; POST /merchants/{merchantId}/webhooks once to subscribe |
webhooks:manage, merchants:read |
Create one key for the website with exactly the scopes in the first rows (Enable the API). The merchant area uses logins instead of the key.
Everything starts with one small helper on your server that adds the credentials. The routes below it are the endpoints your pages call. Replace the LASTMILE_* environment variables with your own values; LASTMILE_API_URL is the base address of the API.
// server.js — Node.js 18+ and Express. The key and secret live in environment variables on this server only.
import express from "express";
import crypto from "node:crypto";
const API = `${process.env.LASTMILE_API_URL}/api/public/v1`;
const app = express();
// One helper that every route uses. The browser never sees the headers.
async function lastmile(path, { method = "GET", body, idempotencyKey, acceptLanguage = "en" } = {}) {
const response = await fetch(`${API}${path}`, {
method,
headers: {
"X-API-Key": process.env.LASTMILE_API_KEY,
"X-API-Secret": process.env.LASTMILE_API_SECRET,
"Accept-Language": acceptLanguage,
...(body ? { "Content-Type": "application/json" } : {}),
...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
},
body: body ? JSON.stringify(body) : undefined,
});
const data = response.status === 204 ? null : await response.json();
return { status: response.status, data };
}
// Webhook route first: it needs the raw body, so it is registered before express.json().
app.post("/hooks/lastmile", express.raw({ type: "application/json" }), (req, res) => {
const expected = crypto.createHmac("sha256", process.env.LASTMILE_WEBHOOK_SECRET).update(req.body).digest("hex");
const received = String(req.get("X-Signature") ?? "");
const ok = expected.length === received.length && crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received));
if (!ok) return res.sendStatus(401);
const event = JSON.parse(req.body.toString("utf8"));
// Save it and answer quickly. Update your own order, notify the customer.
console.log("webhook", event.event, event.data.trackingNumber);
res.sendStatus(200);
});
app.use(express.json());
// ---- Coverage checker: GET /api/coverage?city=جده ----------------------------------------------------------------
app.get("/api/coverage", async (req, res) => {
const query = new URLSearchParams({ country: "SA", city: String(req.query.city ?? "") });
const { status, data } = await lastmile(`/geography/coverage?${query}`);
res.status(status).json(data);
});
// ---- Cities and districts for the form dropdowns (cache these in production) -------------------------------------
app.get("/api/cities", async (_req, res) => {
const { status, data } = await lastmile("/geography/coverage/cities?country=SA&pageSize=100");
res.status(status).json(data);
});
app.get("/api/districts", async (req, res) => {
const query = new URLSearchParams({ country: "SA", city: String(req.query.city ?? ""), pageSize: "100" });
const { status, data } = await lastmile(`/geography/districts?${query}`);
res.status(status).json(data);
});
// ---- Address validation as the customer types: GET /api/resolve?city=...&district=... --------------------------------
app.get("/api/resolve", async (req, res) => {
const query = new URLSearchParams({ country: "SA", city: String(req.query.city ?? ""), district: String(req.query.district ?? "") });
const { status, data } = await lastmile(`/geography/resolve?${query}`);
// 422 carries data.details.candidates: show them as "Did you mean...?" buttons.
res.status(status).json(data);
});
// ---- Price calculator: POST /api/quote ---------------------------------------------------------------------------
app.post("/api/quote", async (req, res) => {
const { fromCity, toCity, weightKg, lengthCm, widthCm, heightCm, codAmount } = req.body;
const { status, data } = await lastmile("/pricing/quote", {
method: "POST",
body: {
pickup: { country: "SA", city: fromCity },
recipient: { country: "SA", city: toCity },
parcel: { weightKg, lengthCm, widthCm, heightCm },
payment: { codAmount: codAmount ?? 0 },
serviceTier: "standard",
},
});
res.status(status).json(data);
});
// ---- Tracking page: GET /api/track/:trackingNumber?phone=1234 -----------------------------------------------------
// The key can read every shipment of the company, so this route decides what a visitor may see:
// the tracking number plus the last 4 digits of the recipient phone.
app.get("/api/track/:trackingNumber", async (req, res) => {
const tn = encodeURIComponent(req.params.trackingNumber);
const shipment = await lastmile(`/shipments/${tn}`);
if (shipment.status !== 200) return res.status(404).json({ message: "Shipment not found" });
const last4 = String(shipment.data.recipient.phone ?? "").replace(/\D/g, "").slice(-4);
if (!last4 || last4 !== String(req.query.phone ?? "")) return res.status(404).json({ message: "Shipment not found" });
const tracking = await lastmile(`/shipments/${tn}/tracking`);
res.status(tracking.status).json(tracking.data); // statuses come in both languages: statusLabelAr / statusLabelEn
});
// ---- "Ship now" form: POST /api/order ----------------------------------------------------------------------------
app.post("/api/order", async (req, res) => {
const order = req.body; // validate this with your own schema first
const { status, data } = await lastmile("/shipments", {
method: "POST",
// Derive the key from YOUR order id: a double click or a retry can never create two shipments.
idempotencyKey: `web-order-${order.id}`,
body: {
reference: `WEB-${order.id}`,
serviceTier: order.express ? "express" : "standard",
sender: { type: "custom", name: order.senderName, phone: order.senderPhone },
pickup: order.pickup, // { country, city, district, addressLine, shortAddress }
recipient: order.recipient, // { country, city, district, addressLine, shortAddress, name, phone }
parcel: order.parcel, // { weightKg, lengthCm, widthCm, heightCm, description }
payment: { codAmount: order.codAmount ?? 0 },
},
});
// 422 geo_* errors: show data.details.candidates. 400: show data.details.errors next to the fields.
res.status(status).json(status === 201 ? { trackingNumber: data.trackingNumber, fee: data.payment.shippingFee } : data);
});
app.listen(3000);// ===== lib/lastmile.ts — server only. Never import this file from a client component. =====
import "server-only";
const API = `${process.env.LASTMILE_API_URL}/api/public/v1`;
export async function lastmile(
path: string,
init: { method?: string; body?: unknown; idempotencyKey?: string; acceptLanguage?: string } = {},
) {
const response = await fetch(`${API}${path}`, {
method: init.method ?? "GET",
cache: "no-store",
headers: {
"X-API-Key": process.env.LASTMILE_API_KEY!,
"X-API-Secret": process.env.LASTMILE_API_SECRET!,
"Accept-Language": init.acceptLanguage ?? "en",
...(init.body ? { "Content-Type": "application/json" } : {}),
...(init.idempotencyKey ? { "Idempotency-Key": init.idempotencyKey } : {}),
},
body: init.body ? JSON.stringify(init.body) : undefined,
});
return { status: response.status, data: await response.json() };
}
// ===== app/api/quote/route.ts — price calculator =====
import { NextResponse } from "next/server";
import { lastmile } from "@/lib/lastmile";
export async function POST(request: Request) {
const { fromCity, toCity, weightKg, lengthCm, widthCm, heightCm } = await request.json();
const { status, data } = await lastmile("/pricing/quote", {
method: "POST",
body: {
pickup: { country: "SA", city: fromCity },
recipient: { country: "SA", city: toCity },
parcel: { weightKg, lengthCm, widthCm, heightCm },
},
});
return NextResponse.json(data, { status });
}
// ===== app/api/track/[trackingNumber]/route.ts — tracking page =====
// The key can read every shipment of the company, so this route decides what a visitor may see:
// the tracking number plus the last 4 digits of the recipient phone.
import { NextResponse } from "next/server";
import { lastmile } from "@/lib/lastmile";
export async function GET(request: Request, { params }: { params: Promise<{ trackingNumber: string }> }) {
const { trackingNumber } = await params;
const phone = new URL(request.url).searchParams.get("phone") ?? "";
const tn = encodeURIComponent(trackingNumber);
const shipment = await lastmile(`/shipments/${tn}`);
const last4 = String(shipment.data?.recipient?.phone ?? "").replace(/\D/g, "").slice(-4);
if (shipment.status !== 200 || !last4 || last4 !== phone) {
return NextResponse.json({ message: "Shipment not found" }, { status: 404 });
}
const tracking = await lastmile(`/shipments/${tn}/tracking`);
return NextResponse.json(tracking.data, { status: tracking.status });
}
// ===== app/api/order/route.ts — "Ship now" form =====
import { NextResponse } from "next/server";
import { lastmile } from "@/lib/lastmile";
export async function POST(request: Request) {
const order = await request.json(); // validate with your own schema first
const { status, data } = await lastmile("/shipments", {
method: "POST",
idempotencyKey: `web-order-${order.id}`, // derived from YOUR order id
body: {
reference: `WEB-${order.id}`,
sender: { type: "custom", name: order.senderName, phone: order.senderPhone },
pickup: order.pickup,
recipient: order.recipient,
parcel: order.parcel,
payment: { codAmount: order.codAmount ?? 0 },
},
});
return NextResponse.json(
status === 201 ? { trackingNumber: data.trackingNumber, fee: data.payment.shippingFee } : data,
{ status },
);
}A key with shipments:read can read every shipment of the company. If your public route returned any shipment for any tracking number, anyone could read other people's names, phones and addresses. So the route above reads the shipment first and answers only when the visitor also supplies the last 4 digits of the recipient's phone, and it returns the timeline, not the whole shipment. Choose the proof that suits your business, but never expose the raw API response of GET /shipments/{trackingNumber}.
The page asks for the tracking number (and the phone check), calls /api/track/... and draws the events list. Each event has statusLabelAr and statusLabelEn, so show the one that matches your page language. Final statuses (delivered, returnedToSender, cancelled, lost, disposed, see the status catalogue) never change again, so stop refreshing the page once the current status is one of them.
Fill the two city dropdowns from GET /geography/coverage/cities (cached on your server, it rarely changes). On submit call /api/quote. If the answer has deliverable: false, show "we do not deliver there yet" instead of a price. Quotes are free and create nothing, so you can quote on every change. See Pricing quotes.
A city input (or the same dropdown) that calls /api/coverage and shows two answers: delivery to this city, pickup from this city. A name that does not match answers 422 geo_city_not_found with suggestions: show them. See Places by name.
- The customer enters the sender, recipient, parcel and addresses. Prefer dropdowns for city and district; if you accept typing, call
/api/resolvewhen the field loses focus and showdetails.candidateson a422. - Show the price from
/api/quotebefore the customer confirms. - On confirm call
/api/order. The server sends the shipment with anIdempotency-Keybuilt from your order id, so a double click or a retried request can never create two shipments. - On
201show thetrackingNumberand offer the label (GET /shipments/{trackingNumber}/label, a PDF) and the tracking link. - On
400show the messages ofdetails.errorsnext to the matching fields; on422with ageo_*code let the customer choose from the candidates.
Merchants sign in with the username and password of their merchant login, created in the dashboard. A merchant login can only see and book its own shipments, so you do not need to filter, and it cannot see anyone else's data. Keep the tokens in a server-side session and refresh them before they expire (Authentication).
// Merchant portal on the same Express server: each merchant signs in with its own username and password.
// The token pair stays in a SERVER-side session; the browser only holds the session cookie.
import session from "express-session"; // use a persistent store (Redis, a database) in production
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, secure: true, sameSite: "lax", maxAge: 8 * 3600 * 1000 },
}),
);
async function asUser(req, path, init = {}) {
const s = req.session.lastmile;
if (!s) return { status: 401, data: { code: "unauthorized" } };
// Refresh one minute early. The refresh token is single use: store the new pair.
if (Date.now() > s.expiresAt) {
const r = await fetch(`${API}/auth/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken: s.refreshToken }),
});
if (!r.ok) {
req.session.destroy(() => {});
return { status: 401, data: { code: "unauthorized" } };
}
const t = await r.json();
req.session.lastmile = { ...t, expiresAt: Date.now() + (t.expiresIn - 60) * 1000 };
}
const response = await fetch(`${API}${path}`, {
...init,
headers: { "Content-Type": "application/json", ...init.headers, Authorization: `Bearer ${req.session.lastmile.accessToken}` },
});
return { status: response.status, data: await response.json() };
}
app.post("/portal/login", async (req, res) => {
const response = await fetch(`${API}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: req.body.username, password: req.body.password }),
});
const tokens = await response.json();
if (!response.ok) return res.status(response.status).json({ code: tokens.code, message: tokens.message });
req.session.lastmile = { ...tokens, expiresAt: Date.now() + (tokens.expiresIn - 60) * 1000 };
res.sendStatus(204);
});
// A merchant login only ever sees its own merchant's shipments: no filter by merchant is needed.
app.get("/portal/shipments", async (req, res) => {
const { status, data } = await asUser(req, `/shipments?page=${Number(req.query.page) || 1}&pageSize=25`);
res.status(status).json(data);
});
app.post("/portal/shipments", async (req, res) => {
const { status, data } = await asUser(req, "/shipments", {
method: "POST",
headers: { "Idempotency-Key": `portal-${req.session.id}-${req.body.clientRequestId}` },
body: JSON.stringify({
reference: req.body.reference,
// sender is optional for a merchant login: it always sends as its own merchant, from its primary address
recipient: req.body.recipient,
parcel: req.body.parcel,
payment: { codAmount: req.body.codAmount ?? 0 },
}),
});
res.status(status).json(data);
});Subscribe once per merchant and let your server receive the events. A signed delivery arrives at /hooks/lastmile (already in the server above). Update the order in your database, then notify the customer by SMS or e-mail. See Webhooks.
curl -X POST "https://api.goldrock.live/api/public/v1/merchants/3fa85f64-5717-4562-b3fc-2c963f66afa6/webhooks" \
-H "X-API-Key: lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
-H "X-API-Secret: YOUR_API_SECRET" \
-H "Content-Type: application/json" \
-d '{
"url": "https://shop.example.com/hooks/lastmile",
"events": [
"shipment.created",
"shipment.out_for_delivery",
"shipment.delivered"
],
"description": "Order system"
}'const response = await fetch("https://api.goldrock.live/api/public/v1/merchants/3fa85f64-5717-4562-b3fc-2c963f66afa6/webhooks", {
method: "POST",
headers: {
"X-API-Key": "lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"X-API-Secret": "YOUR_API_SECRET",
"Content-Type": "application/json"
},
body: JSON.stringify({
"url": "https://shop.example.com/hooks/lastmile",
"events": [
"shipment.created",
"shipment.out_for_delivery",
"shipment.delivered"
],
"description": "Order system"
}),
});
const data = await response.json();
console.log(response.status, data);<?php
$url = 'https://api.goldrock.live/api/public/v1/merchants/3fa85f64-5717-4562-b3fc-2c963f66afa6/webhooks';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'X-API-Key: lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'X-API-Secret: YOUR_API_SECRET',
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'url' => 'https://shop.example.com/hooks/lastmile',
'events' => [
'shipment.created',
'shipment.out_for_delivery',
'shipment.delivered',
],
'description' => 'Order system',
], JSON_UNESCAPED_UNICODE),
]);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($status, json_decode($result, true));import requests
response = requests.request(
"POST",
"https://api.goldrock.live/api/public/v1/merchants/3fa85f64-5717-4562-b3fc-2c963f66afa6/webhooks",
headers={
"X-API-Key": "lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"X-API-Secret": "YOUR_API_SECRET",
},
json={
"url": "https://shop.example.com/hooks/lastmile",
"events": [
"shipment.created",
"shipment.out_for_delivery",
"shipment.delivered",
],
"description": "Order system",
},
timeout=30,
)
print(response.status_code, response.json())- The key and secret are only in server environment variables.
- Your own public routes (
/api/track,/api/quote,/api/order) have rate limiting or a CAPTCHA, because they spend your API quota (120 requests per minute per key). - You cache countries, cities, districts and statuses.
- Every create sends an
Idempotency-Keythat comes from your own data. - You map error
codes to friendly messages in both languages, and showdetails.candidatesfor places. - You verify webhook signatures and answer
2xxfast. - You never send the API's raw error
messageto a customer without checking it reads well on your page.