A flight status page is one of the most useful things you can build with flight data: type in BA117 and see whether it's on time, which gate it leaves from, and when it lands. It's also a good first project, because it touches everything a real integration needs. You have to keep a key secret, handle a flight that isn't operating, and avoid paying for the same answer a thousand times.
This tutorial builds one with Next.js and TypeScript, using the official SkyLink SDK. By the end you'll have:
- a page at
/flight/BA117that shows status, times, delay, terminal and gate - a delay in minutes, worked out from the board times
- caching, so a flight costs at most one API request every two minutes, however many people are watching
- a page that refreshes itself without the browser ever seeing your API key
- a small JSON endpoint for a mobile app or a widget
The code targets the App Router on Next.js 15 or 16. We built and ran it against a mock of the API on Next.js 16 to check that it behaves as described.
What you need
- Node 20 or newer
- A SkyLink API key. Plans start at $19 a month, and the key is issued at checkout. There's also a Free Trial by application for personal, non-commercial projects.
Create the app and install the SDK:
npx create-next-app@latest flight-status --typescript --app
cd flight-status
npm install skylink-api server-onlyPut your key in .env.local, which Next.js keeps out of git by default:
SKYLINK_API_KEY=your-keyDon't prefix it with NEXT_PUBLIC_. That prefix tells Next.js to ship the value to the browser, which is exactly what you don't want.
Step 1: fetch the flight on the server
Everything that touches the API lives in one file, lib/flight.ts. It creates the client, validates the flight number, fetches the status and turns the response into the shape the page needs.
import "server-only";
import { NotFoundError, SkyLink } from "skylink-api";
// One client for the whole server. The key is read here and never leaves it.
// A page shouldn't hang on a slow upstream: one retry, eight seconds at most per try.
const sky = new SkyLink({
provider: "direct",
apiKey: process.env.SKYLINK_API_KEY,
maxRetries: 1,
timeout: 8_000,
});
export type Leg = {
airport: string;
scheduled: string | null; // local board time, e.g. "08:25"
latest: string | null; // actual departure or estimated arrival
delayMinutes: number | null;
terminal: string | null;
gate: string | null;
};
export type FlightView = {
flight: string;
airline: string;
status: string;
cancelled: boolean;
departure: Leg;
arrival: Leg & { baggage: string | null };
};
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
/** "24 Nov" + "08:25" -> minutes since the start of the year. The API sends no year. */
function boardMinutes(date?: string, time?: string): number | null {
const d = /^(\d{1,2}) (\w{3})$/.exec(date ?? "");
const t = /^(\d{1,2}):(\d{2})$/.exec(time ?? "");
if (!d || !t) return null;
const month = MONTHS.indexOf(d[2]);
if (month < 0) return null;
return Date.UTC(2024, month, Number(d[1]), Number(t[1]), Number(t[2])) / 60_000;
}
function delay(schedDate?: string, schedTime?: string, lateDate?: string, lateTime?: string): number | null {
const sched = boardMinutes(schedDate, schedTime);
const late = boardMinutes(lateDate, lateTime);
if (sched === null || late === null) return null;
let minutes = late - sched;
if (minutes < -12 * 60) minutes += 366 * 24 * 60; // scheduled 31 Dec, left 1 Jan
return Math.round(minutes);
}
const text = (value?: string) => (value && value !== "--" ? value : null);
/** IATA or ICAO flight number: BA117, BAW117, U28001, FR1730. */
export function normalizeFlightNumber(input: string): string | null {
const value = input.replace(/\s+/g, "").toUpperCase();
return /^[A-Z0-9]{2,3}\d{1,4}[A-Z]?$/.test(value) ? value : null;
}
/** Today's status for one flight, or null when it isn't operating. */
export async function getFlight(number: string): Promise<FlightView | null> {
let s;
try {
s = await sky.flightStatus(number);
} catch (error) {
if (error instanceof NotFoundError) return null;
throw error;
}
const dep = s.departure ?? {};
const arr = s.arrival ?? {};
return {
flight: s.flight_number,
airline: s.airline,
status: s.status,
cancelled: /cancel/i.test(s.status),
departure: {
airport: dep.airport_full ?? dep.airport ?? "Unknown",
scheduled: text(dep.scheduled_time),
latest: text(dep.actual_time),
delayMinutes: delay(dep.scheduled_date, dep.scheduled_time, dep.actual_date, dep.actual_time),
terminal: text(dep.terminal),
gate: text(dep.gate),
},
arrival: {
airport: arr.airport_full ?? arr.airport ?? "Unknown",
scheduled: text(arr.scheduled_time),
latest: text(arr.estimated_time),
delayMinutes: delay(arr.scheduled_date, arr.scheduled_time, arr.estimated_date, arr.estimated_time),
terminal: text(arr.terminal),
gate: text(arr.gate),
baggage: text(arr.baggage),
},
};
}Five things in that file are worth a closer look.
import "server-only". If anyone ever imports this file from a client component, the build fails with a clear error. It's a one-line guard against the most expensive mistake in this project, which is leaking the key.
provider: "direct". The SDK's default channel is RapidAPI. If you bought your key from SkyLink directly and leave this out, you get a 401. If you subscribed through RapidAPI, remove the line and set RAPIDAPI_KEY instead.
One retry and an eight-second limit. The SDK's defaults suit a background job: three retries and 30 seconds per attempt. A person waiting for a page shouldn't wait that long, so the client here is stricter.
The times are board times. The API returns local clock times and dates as an airport board shows them, such as 08:25 and 28 Nov, with no year and no time zone. Don't pass them to new Date(). The delay is the difference between two times at the same airport, so boardMinutes only needs the day, month, hour and minute. It also handles a flight scheduled for 31 December that leaves on 1 January.
Missing data is normal. A gate that hasn't been announced arrives as an empty string, and a leg can arrive as an empty object when the source had no card for it. The text helper and the ?? fallbacks turn all of that into null, so the page can show a dash.
normalizeFlightNumber does two jobs. It tidies input like ba 117, and it rejects anything that isn't shaped like a flight number before it gets near a URL.

Step 2: the page
The page is a server component at app/flight/[number]/page.tsx. It runs on the server, calls getFlight directly, and sends finished HTML to the browser.
import { notFound } from "next/navigation";
import { getFlight, normalizeFlightNumber, type Leg } from "@/lib/flight";
import { LiveRefresh } from "./live-refresh";
export const revalidate = 120; // one upstream request per flight every two minutes, at most
// No pages are built ahead of time. Each flight page is rendered on its first
// visit, then served from the cache until it is two minutes old.
export function generateStaticParams() {
return [];
}
function delayLabel(minutes: number | null) {
if (minutes === null) return "";
if (minutes > 15) return `${minutes} min late`;
if (minutes < -5) return `${-minutes} min early`;
return "On time";
}
function LegCard({ title, leg }: { title: string; leg: Leg }) {
return (
<section>
<h2>{title}</h2>
<p>{leg.airport}</p>
<p>
Scheduled {leg.scheduled ?? "—"} · Latest {leg.latest ?? "—"} {delayLabel(leg.delayMinutes)}
</p>
<p>
Terminal {leg.terminal ?? "—"} · Gate {leg.gate ?? "—"}
</p>
</section>
);
}
export default async function FlightPage({ params }: { params: Promise<{ number: string }> }) {
const { number: raw } = await params;
const number = normalizeFlightNumber(raw);
if (!number) notFound();
const flight = await getFlight(number);
if (!flight) notFound();
return (
<main>
<h1>
{flight.flight} · {flight.airline}
</h1>
<p role="status">{flight.status}</p>
<LegCard title="Departure" leg={flight.departure} />
<LegCard title="Arrival" leg={flight.arrival} />
<p>Baggage belt {flight.arrival.baggage ?? "—"}</p>
<LiveRefresh seconds={120} />
</main>
);
}Two lines do the caching. revalidate = 120 tells Next.js to keep each rendered page for two minutes. The empty generateStaticParams is what switches that on for a dynamic route: no pages are built in advance, but each one is cached after its first visit.
The effect is that a thousand people watching BA117 cost one API request every two minutes, not a thousand. When we ran this, five repeat visits to the same flight made no upstream requests at all.
Two minutes is a sensible interval. The underlying times don't change faster than that, and the flight status docs suggest polling every two to five minutes.
A flight that isn't operating today returns a 404 from the API, getFlight turns that into null, and notFound() shows your app's not-found page. The same happens for input that isn't a flight number.
The markup is deliberately plain so the logic is easy to see. Add your own styles; the image above shows one way the finished page could look.
The 15-minute threshold in delayLabel follows the usual convention that a flight within 15 minutes of schedule counts as on time.
Step 3: live refresh without a client fetch
The page should update while someone watches it. The obvious way is to fetch from the browser, but there's a simpler one. A tiny client component asks Next.js to re-render the server component on a timer:
"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
/** Re-renders the server component on a timer. No flight data is fetched in the browser. */
export function LiveRefresh({ seconds }: { seconds: number }) {
const router = useRouter();
useEffect(() => {
const timer = setInterval(() => {
if (document.visibilityState === "visible") router.refresh();
}, seconds * 1000);
return () => clearInterval(timer);
}, [router, seconds]);
return null;
}router.refresh() re-runs the page on the server and patches the result into the browser. The cache from step 2 still applies, so a refresh inside the two-minute window costs nothing. The visibility check stops background tabs from refreshing at all.
The browser never fetches flight data and never sees the key. When we searched the built JavaScript bundles and the page HTML for the key, it wasn't there.

Step 4: a JSON endpoint for other clients
If a mobile app or an embedded widget needs the same data, add a route handler at app/api/flight/[number]/route.ts:
import { RateLimitError } from "skylink-api";
import { getFlight, normalizeFlightNumber } from "@/lib/flight";
export async function GET(_request: Request, context: { params: Promise<{ number: string }> }) {
const { number: raw } = await context.params;
const number = normalizeFlightNumber(raw);
if (!number) {
return Response.json({ error: "Not a flight number" }, { status: 400 });
}
try {
const flight = await getFlight(number);
if (!flight) {
return Response.json({ error: "Not operating today" }, { status: 404 });
}
return Response.json(flight, {
// Let the CDN answer repeat requests for two minutes: many viewers, one upstream call.
headers: { "Cache-Control": "public, s-maxage=120, stale-while-revalidate=60" },
});
} catch (error) {
if (error instanceof RateLimitError) {
const seconds = Math.ceil((error.retryAfter ?? 5_000) / 1000);
return Response.json({ error: "Busy, try again shortly" },
{ status: 429, headers: { "Retry-After": String(seconds) } });
}
console.error("flight status failed", error);
return Response.json({ error: "Flight data unavailable" }, { status: 502 });
}
}The status codes are deliberate. A malformed number is a 400, a flight that isn't operating is a 404, a rate limit passes through as a 429 with a Retry-After header, and anything else becomes a 502 so your clients can tell "no such flight" from "the data source had a problem".
The Cache-Control header lets a CDN in front of your app, such as Vercel's or Netlify's, answer repeat requests for two minutes. Without a CDN, every call to this route reaches SkyLink, so put a cache in front of it or add your own rate limit. An open endpoint that spends your quota is worth protecting either way.
Try it
npm run devOpen http://localhost:3000/flight/BA117, with any flight operating today. Then check the endpoint:
curl -i http://localhost:3000/api/flight/BA117Note that caching only works fully in a production build. In development Next.js re-renders on every request, so test the cache with npm run build and npm start.
Deploying
Set SKYLINK_API_KEY as an environment variable in your host's dashboard, and deploy as you would any Next.js app. Nothing else is needed. Two things to check after the first deploy:
- The key isn't public. View the page source and search the JavaScript files for the first few characters of your key. You should find nothing.
- Links use one spelling.
/flight/BA117and/flight/ba117both work, but they're cached separately. Link to the uppercase form everywhere.
What it costs to run
With a two-minute cache, a flight page that's being watched uses at most 30 requests an hour. A ten-hour flight watched from gate to gate is about 300 requests, no matter how many people follow it.
| Plan | Requests a month | Hours of watched flights |
|---|---|---|
| Free Trial | 1,000 | About 33 |
| Basic, $19 | 5,000 | About 167 |
| Pro, $59 | 20,000 | About 667 |
Flights nobody is looking at cost nothing, because nothing is polling in the background. If your product needs to notify people when they're not looking, that's what webhooks on the Pro plan are for. For volumes beyond the plans, our sales team is always available to negotiate the best deal: get in touch.
Where to take it next
An airport board. The SDK's sky.schedules.departures({ iata: "LHR" }) returns a whole departure board in one request. The rows use capitalised keys such as Flight and Status. Building a departure board shows the idea on a Raspberry Pi.
A map. Live positions come from sky.adsb.aircraft(), but aircraft broadcast a callsign such as BAW117, not the flight number BA117. Callsign vs flight number explains the difference before you wire the two together.
Weather at the destination. sky.weather.metar("KJFK", { parsed: true }) adds current conditions, which often explain a delay.
Alerts. Building a delay notification system covers the server side of telling users when something changes.
The SDK quickstart covers the rest of the TypeScript client, and the flight status API guide goes through every field in the response.

