Mastodon

Tutorial

Find the nearest bus stop with Supabase and PostGIS

Every bus rider asks two questions: where's the nearest stop, and when's the next bus? The first answer barely changes. The second changes every few seconds. Supabase handles both: Postgres and PostGIS for the stops, and an Edge Function for the live buses.

· Next.js · Supabase · one free API key

In this tutorial we'll build both halves for Penang, Malaysia: all 1,932 Rapid Penang bus stops in Postgres, the three nearest to any point, and their next buses from an Edge Function. The demo runs on a self-hosted Supabase, and every step works on a free Supabase Cloud project too.

How it works

You pick
Komtar
A place in Penang (5.4145, 100.3296), or your own location
Supabase
1. nearby_stops() in Postgres
PostGIS sorts all 1,932 stops by distance and returns the 3 closest
2. The live-arrivals Edge Function
Adds the Malaysia Transit API key and asks for the next buses
You get
Terminal Komtar, 87 m away
Route 101 to Hub Teluk Bahang in 1 min, plus the next buses at two more stops
One database function and one Edge Function between a place and its next bus. Real results from 24 November 2026.

Stops stay where they are for years, so they live in the database, where PostGIS finds the nearest ones in milliseconds. Arrivals change every few seconds, so an Edge Function fetches them when the page asks, with an API key the browser never sees.

What you need

  • Node.js 22.9 or newer.
  • A Supabase project. A free one on works, and so does . Either way, use the new API keys: a publishable key for the browser and a secret key for scripts.
  • The Supabase CLI. npx supabase runs it without a global install.
  • A Malaysia Transit API key. It's free from the .

Step 1: Store the stops with PostGIS

PostGIS adds geographic types and distance queries to Postgres. installs it in the extensions schema, never in public. Here's the start of the migration:

sql
create extension if not exists postgis with schema extensions;

create table public.stops (
  stop_id text primary key,
  stop_code text,
  stop_name text not null,
  location extensions.geography(point) not null
);

create index stops_location_idx on public.stops using gist (location);

Three choices matter here:

  • Geography, not geometry. Geography works in metres on a round Earth, so distances come out in real units.
  • A GiST index. It keeps “nearest stops” fast as the table grows.
  • Read-only Row Level Security. Bus stops are public, so anyone can read them, but nobody can write through the API.
sql
alter table public.stops enable row level security;

create policy "Anyone can read stops"
  on public.stops for select
  to anon, authenticated
  using (true);

With no insert, update or delete policy, the publishable key can't change a thing. I checked: an insert fails with Postgres error 42501, and an update matches no rows.

Step 2: Load 1,932 stops from data.gov.my

Malaysia's open data portal, , publishes Rapid Penang's timetable as a GTFS feed: a zip of CSV files. We only need stops.txt. The loader, scripts/load-stops.js, downloads the zip, unzips that one file and parses it:

js
const files = unzipSync(new Uint8Array(await response.arrayBuffer()), {
  filter: (file) => file.name === "stops.txt",
});
const rows = parse(strFromU8(files["stops.txt"]), { columns: true, bom: true, skip_empty_lines: true });

const stops = rows.map((row) => ({
  stop_id: row.stop_id,
  stop_code: row.stop_code || null,
  stop_name: row.stop_name,
  // PostGIS reads this text format: longitude first, then latitude, with a space between.
  location: `POINT(${row.stop_lon} ${row.stop_lat})`,
}));

Watch the order in POINT(...). Longitude comes first, because it's the x-axis. Swap them and PostGIS won't stop you. It folds the impossible latitude of 100 back into range, with only a notice most clients never show, and puts Komtar in the Arctic between Greenland and Svalbard.

The loader saves 500 stops at a time with upsert, so you can run it again whenever the feed changes:

js
const { error } = await supabase.from("stops").upsert(batch, { onConflict: "stop_id" });

It writes with your secret key, which bypasses Row Level Security, so it runs on your machine and nowhere else. Put your project URL and keys in .env.local, then:

bash
npm run load-stops
Output
Downloading the Rapid Penang GTFS feed from data.gov.my...
Found 1932 stops.
Saved 500 of 1932
Saved 1000 of 1932
Saved 1500 of 1932
Saved 1932 of 1932
Done.

Step 3: Find the nearest stops with one function

PostGIS's <-> operator sorts by distance and uses the GiST index, so it doesn't measure the distance to every stop. Wrap it in a database function and Supabase exposes it to the client as an RPC:

sql
create or replace function public.nearby_stops(
  user_lat float,
  user_lon float,
  max_results int default 3
)
returns table (stop_id text, stop_name text, lat float, lon float, dist_meters float)
language sql
stable
set search_path = ''
as $$
  select
    s.stop_id,
    s.stop_name,
    extensions.st_y(s.location::extensions.geometry) as lat,
    extensions.st_x(s.location::extensions.geometry) as lon,
    extensions.st_distance(s.location, extensions.st_point(user_lon, user_lat)::extensions.geography) as dist_meters
  from public.stops s
  order by s.location operator(extensions.<->) extensions.st_point(user_lon, user_lat)::extensions.geography
  limit least(greatest(max_results, 1), 10);
$$;
  • set search_path = '' is what Supabase recommends for functions, and it's why every name is written in full, like extensions.st_distance.
  • The inputs are user_lat and user_lon, not lat and lon, so they don't clash with the output columns.
  • The limit is capped at 10, so nobody can ask for every stop at once.

From the browser, it's one call with the publishable key:

ts
const { data, error } = await supabase().rpc("nearby_stops", { user_lat: lat, user_lon: lon, max_results: 3 });

For Komtar, George Town's landmark tower, it returned these on 24 November 2026. They're straight-line distances, not walking routes:

Result, rounded to the metre
12002116  Terminal Komtar    87 m
12001060  Komtar Utara       97 m
12002213  Komtar II         154 m

Step 4: Live arrivals in an Edge Function

The Malaysia Transit API knows where every bus is, but it needs an API key. Put that key in the browser and anyone can copy it. So the page asks an Edge Function, and the function adds the key from its secrets.

The function uses withSupabase from @supabase/server, the pattern in . With auth: "publishable", it only answers requests that carry your project's publishable key. That key isn't a JWT, so supabase/config.toml sets verify_jwt = false for this function:

ts
const handler = withSupabase({ auth: "publishable" }, async (req) => {
  const apiKey = Deno.env.get("MALAYSIA_TRANSIT_API_KEY");
  // ...check stop_id, then:
  const response = await fetch(`${TRANSIT_API}/stops/${stopId}/arrivals?area=${area}`, {
    headers: { "X-API-Key": apiKey },
  });
  const data = await response.json();
  const arrivals = ((data.arrivals ?? []) as Arrival[]).slice(0, 4).map((bus) => ({
    route: bus.routeShortName,
    destination: bus.destination,
    minutes: bus.etaMinutes,
    live: bus.isRealtime === true,
  }));
  return Response.json({ stop_id: stopId, stop_name: data.stopName ?? null, arrivals });
});

It does three smaller jobs too:

  • Checks the stop ID. Only plain IDs go into the API's URL.
  • Answers the browser's CORS check. The OPTIONS request gets its reply before withSupabase sees it.
  • Trims the answer. Four buses and four fields, not the API's full record.

A publishable key is public, so this keeps out stray traffic, not a determined caller. Add rate limiting before you rely on it. Here's Terminal Komtar, trimmed:

Response
{
  "stop_id": "12002116",
  "stop_name": "Terminal Komtar",
  "arrivals": [
    { "route": "101", "destination": "Hub Teluk Bahang", "minutes": 1, "live": true },
    { "route": "103", "destination": "KOMTAR-PULAU TIKUS-KOMTAR", "minutes": 1, "live": true }
  ]
}

Deploy it on Supabase Cloud

bash
npx supabase secrets set --env-file supabase/functions/.env
npx supabase functions deploy live-arrivals --use-api

--use-api bundles the function on Supabase's side, so you don't need Docker.

Self-hosted Supabase

On a self-hosted stack, functions live in volumes/functions:

  1. Copy the function. Put supabase/functions/live-arrivals into volumes/functions/live-arrivals.
  2. Add the key. Put MALAYSIA_TRANSIT_API_KEY in the functions service's environment, for example an .env.functions file loaded with env_file.
  3. Restart it. Run sh run.sh recreate functions. A plain restart picks up new code, but new secrets need a recreate.
  4. Check the imports. Self-hosted functions share one import map, volumes/functions/deno.jsonc, instead of each function's own deno.json. Make sure @supabase/server and @supabase/functions-js are in it.

Run the migration with psql inside the database container:

bash
docker compose exec -T db psql -U postgres -d postgres -1 < supabase/migrations/20261122120000_bus_stops.sql

Step 5: The page

The page makes the two calls in order: first the nearest stops, then live arrivals for all three at once:

ts
const withBuses = await Promise.all(
  nearest.map(async (stop): Promise<StopWithBuses> => {
    const { data, error } = await supabase().functions.invoke("live-arrivals", {
      body: { stop_id: stop.stop_id },
    });
    if (error) return { ...stop, buses: [], problem: "Live arrivals are unavailable right now." };
    return { ...stop, buses: data.arrivals as Bus[] };
  }),
);

The stops appear first, because Postgres answers straight away:

The page right after choosing Komtar: Terminal Komtar 87 m away, Komtar Utara 97 m away and Komtar II 154 m away, each still checking live arrivals.
Right after choosing Komtar: the three nearest stops, with live arrivals on the way.

Then each stop fills in with its next buses:

The same page a moment later. Terminal Komtar shows routes 12, 101 and 301 due in a minute, and Komtar Utara shows routes CT15, 301, 502 and 202 due in one to four minutes.
A moment later: live buses at Terminal Komtar and Komtar Utara on 24 November 2026. Live times change.

“Use my location” asks the browser where you are. Most people trying it won't be in Penang, so there are three places to pick too: Komtar, Kek Lok Si Temple and Penang Airport. On a phone, the buttons wrap and each stop gets the full width:

The page on a phone: Terminal Komtar, 87 m away, with routes 301, 101 and 103 due in a minute and route 12 in two.
The same page on a phone.

The whole project is , and here are the four files in full:

The migration (52 lines)
supabase/migrations/20261122120000_bus_stops.sql
-- Bus stops with a location column, and a function that finds the nearest ones.

-- PostGIS adds geographic types and distance queries to Postgres. Supabase's
-- guide installs it in the extensions schema, never in public.
create extension if not exists postgis with schema extensions;

-- One row per bus stop, from the operator's GTFS feed (stops.txt).
create table public.stops (
  stop_id text primary key,
  stop_code text,
  stop_name text not null,
  location extensions.geography(point) not null
);

-- A spatial index keeps "nearest stops" fast as the table grows.
create index stops_location_idx on public.stops using gist (location);

-- Bus stops are public information, so anyone can read them. Nobody can write
-- through the API: the loader script uses the secret key, which bypasses RLS.
alter table public.stops enable row level security;

create policy "Anyone can read stops"
  on public.stops for select
  to anon, authenticated
  using (true);

grant select on public.stops to anon, authenticated;

-- The nearest stops to a point, closest first, with the distance in metres.
-- The <-> operator sorts by distance and uses the spatial index.
create or replace function public.nearby_stops(
  user_lat float,
  user_lon float,
  max_results int default 3
)
returns table (stop_id text, stop_name text, lat float, lon float, dist_meters float)
language sql
stable
set search_path = ''
as $$
  select
    s.stop_id,
    s.stop_name,
    extensions.st_y(s.location::extensions.geometry) as lat,
    extensions.st_x(s.location::extensions.geometry) as lon,
    extensions.st_distance(s.location, extensions.st_point(user_lon, user_lat)::extensions.geography) as dist_meters
  from public.stops s
  order by s.location operator(extensions.<->) extensions.st_point(user_lon, user_lat)::extensions.geography
  limit least(greatest(max_results, 1), 10);
$$;

grant execute on function public.nearby_stops(float, float, int) to anon, authenticated;
The Edge Function (77 lines)
supabase/functions/live-arrivals/index.ts
/**
 * live-arrivals: the next buses at one bus stop, from the Malaysia Transit API.
 *
 * The page sends a stop ID. This function adds the Malaysia Transit API key,
 * which lives in Supabase as an Edge Function secret, calls the API, and trims
 * the answer to what the page shows. The key never reaches the browser.
 */
import "@supabase/functions-js/edge-runtime.d.ts";
import { withSupabase } from "@supabase/server";

const TRANSIT_API = "https://malaysiatransit.techmavie.digital/api";

/** The page calls this function from another origin, so it answers CORS checks. */
const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
  "Access-Control-Allow-Methods": "POST, OPTIONS",
};

/** The fields of a Malaysia Transit arrival that the page uses. */
interface Arrival {
  routeShortName: string;
  destination: string;
  etaMinutes: number;
  isRealtime: boolean;
}

// 'publishable' only lets through requests that carry this project's
// publishable key. That key is public, so this keeps out stray traffic,
// not a determined caller: add rate limiting before you rely on it.
const handler = withSupabase({ auth: "publishable" }, async (req) => {
  const apiKey = Deno.env.get("MALAYSIA_TRANSIT_API_KEY");
  if (!apiKey) {
    return Response.json({ error: "MALAYSIA_TRANSIT_API_KEY is not set" }, { status: 500 });
  }

  const body = await req.json().catch(() => ({}));
  const stopId = String(body.stop_id ?? "");
  const area = String(body.area ?? "penang");

  // Both values go into the API's URL, so accept only plain IDs.
  if (!/^[A-Za-z0-9_-]{1,40}$/.test(stopId)) {
    return Response.json({ error: 'Send a stop ID, like {"stop_id": "12002116"}' }, { status: 400 });
  }
  if (!/^[a-z-]{2,30}$/.test(area)) {
    return Response.json({ error: "area should look like penang or klang-valley" }, { status: 400 });
  }

  const response = await fetch(`${TRANSIT_API}/stops/${stopId}/arrivals?area=${area}`, {
    headers: { "X-API-Key": apiKey },
  });
  if (!response.ok) {
    return Response.json({ error: `Malaysia Transit API returned ${response.status}` }, { status: 502 });
  }

  const data = await response.json();
  const arrivals = ((data.arrivals ?? []) as Arrival[]).slice(0, 4).map((bus) => ({
    route: bus.routeShortName,
    destination: bus.destination,
    minutes: bus.etaMinutes,
    live: bus.isRealtime === true,
  }));

  return Response.json({ stop_id: stopId, stop_name: data.stopName ?? null, arrivals });
});

export default {
  async fetch(req: Request) {
    // Answer the browser's CORS preflight before any key check.
    if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });

    const response = await handler(req);
    const headers = new Headers(response.headers);
    for (const [name, value] of Object.entries(corsHeaders)) headers.set(name, value);
    return new Response(response.body, { status: response.status, headers });
  },
};
The loader (64 lines)
scripts/load-stops.js
/**
 * Loads Rapid Penang's bus stops into Supabase.
 *
 *   1. Download the operator's GTFS feed from data.gov.my: a zip of CSV files.
 *   2. Read stops.txt from it.
 *   3. Upsert every stop into public.stops, 500 at a time.
 *
 * It writes with your secret key, which bypasses Row Level Security, so it
 * runs here on your machine and never in a browser.
 *
 *   npm run load-stops              load the stops
 *   npm run load-stops -- --dry-run  just download and parse, to check the feed
 */
import { createClient } from "@supabase/supabase-js";
import { parse } from "csv-parse/sync";
import { strFromU8, unzipSync } from "fflate";

const FEED_URL = "https://api.data.gov.my/gtfs-static/prasarana?category=rapid-bus-penang";
const BATCH_SIZE = 500;
const dryRun = process.argv.includes("--dry-run");

/** Reads a required environment variable, with a clear message if it's missing. */
function requireEnv(name) {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is not set. Copy .env.example to .env.local and fill it in.`);
  return value;
}

console.log("Downloading the Rapid Penang GTFS feed from data.gov.my...");
const response = await fetch(FEED_URL);
if (!response.ok) throw new Error(`data.gov.my returned ${response.status}`);

// Unzip only the file we need, then parse the CSV into one object per row.
const files = unzipSync(new Uint8Array(await response.arrayBuffer()), {
  filter: (file) => file.name === "stops.txt",
});
const rows = parse(strFromU8(files["stops.txt"]), { columns: true, bom: true, skip_empty_lines: true });

const stops = rows.map((row) => ({
  stop_id: row.stop_id,
  stop_code: row.stop_code || null,
  stop_name: row.stop_name,
  // PostGIS reads this text format: longitude first, then latitude, with a space between.
  location: `POINT(${row.stop_lon} ${row.stop_lat})`,
}));
console.log(`Found ${stops.length} stops.`);

if (dryRun) {
  console.log("Dry run, so nothing was written. The first three:");
  console.table(stops.slice(0, 3));
  process.exit(0);
}

const supabase = createClient(requireEnv("NEXT_PUBLIC_SUPABASE_URL"), requireEnv("SUPABASE_SECRET_KEY"), {
  auth: { persistSession: false },
});

for (let i = 0; i < stops.length; i += BATCH_SIZE) {
  const batch = stops.slice(i, i + BATCH_SIZE);
  const { error } = await supabase.from("stops").upsert(batch, { onConflict: "stop_id" });
  if (error) throw new Error(`Saving stops failed: ${error.message}`);
  console.log(`Saved ${i + batch.length} of ${stops.length}`);
}
console.log("Done.");
The page (153 lines)
app/page.tsx
"use client";

import { useState } from "react";
import { supabase } from "../lib/supabase";

/** Places to try from anywhere in the world: the stops are all in Penang. */
const PLACES = [
  { name: "Komtar", lat: 5.4145, lon: 100.3296 },
  { name: "Kek Lok Si Temple", lat: 5.3996, lon: 100.2736 },
  { name: "Penang Airport", lat: 5.2926, lon: 100.2648 },
];

/** A row from the nearby_stops database function. */
interface Stop {
  stop_id: string;
  stop_name: string;
  lat: number;
  lon: number;
  dist_meters: number;
}

/** One bus, as the live-arrivals Edge Function returns it. */
interface Bus {
  route: string;
  destination: string;
  minutes: number;
  live: boolean;
}

/** A stop and its buses: null while they load. */
interface StopWithBuses extends Stop {
  buses: Bus[] | null;
  problem?: string;
}

export default function Home() {
  const [origin, setOrigin] = useState("");
  const [stops, setStops] = useState<StopWithBuses[]>([]);
  const [status, setStatus] = useState<"idle" | "loading" | "done" | "error">("idle");
  const [message, setMessage] = useState("");

  async function findStops(label: string, lat: number, lon: number) {
    setOrigin(label);
    setStatus("loading");
    setMessage("");
    setStops([]);

    // Step 1: PostGIS finds the three nearest stops, through a database function.
    const { data, error } = await supabase().rpc("nearby_stops", { user_lat: lat, user_lon: lon, max_results: 3 });
    if (error) {
      setStatus("error");
      setMessage(error.message);
      return;
    }
    const nearest = (data ?? []) as Stop[];
    setStops(nearest.map((stop) => ({ ...stop, buses: null })));

    // Step 2: the Edge Function fetches live arrivals for each stop, all at once.
    const withBuses = await Promise.all(
      nearest.map(async (stop): Promise<StopWithBuses> => {
        const { data, error } = await supabase().functions.invoke("live-arrivals", {
          body: { stop_id: stop.stop_id },
        });
        if (error) return { ...stop, buses: [], problem: "Live arrivals are unavailable right now." };
        return { ...stop, buses: data.arrivals as Bus[] };
      }),
    );
    setStops(withBuses);
    setStatus("done");
  }

  function locateMe() {
    if (!navigator.geolocation) {
      setStatus("error");
      setMessage("This browser can't share its location. Pick a place instead.");
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (position) => findStops("you", position.coords.latitude, position.coords.longitude),
      () => {
        setStatus("error");
        setMessage("Location access was declined. Pick a place instead.");
      },
    );
  }

  return (
    <main>
      <p className="kicker">Supabase + Malaysia Transit</p>
      <h1>Nearest bus stop</h1>
      <p className="lede">
        Rapid Penang&apos;s 1,932 bus stops live in Supabase Postgres. PostGIS finds the closest ones, and an Edge
        Function asks the Malaysia Transit API when the next buses arrive.
      </p>

      <div className="actions">
        <button type="button" className="primary" onClick={locateMe}>
          Use my location
        </button>
        {PLACES.map((place) => (
          <button key={place.name} type="button" onClick={() => findStops(place.name, place.lat, place.lon)}>
            {place.name}
          </button>
        ))}
      </div>
      <p className="hint">Not in Penang? Pick one of the places.</p>

      {status === "loading" && stops.length === 0 && <p className="muted">Finding stops near {origin}...</p>}
      {status === "error" && <p className="problem">{message}</p>}

      {stops.length > 0 && (
        <section aria-live="polite">
          <h2>Closest stops to {origin}</h2>
          <ol className="stops">
            {stops.map((stop) => (
              <li key={stop.stop_id}>
                <div className="stop-head">
                  <strong>{stop.stop_name}</strong>
                  <span className="distance">{Math.round(stop.dist_meters)} m away</span>
                </div>
                {stop.buses === null ? (
                  <p className="muted">Checking live arrivals...</p>
                ) : stop.problem ? (
                  <p className="muted">{stop.problem}</p>
                ) : stop.buses.length === 0 ? (
                  <p className="muted">No buses due right now.</p>
                ) : (
                  <ul className="buses">
                    {stop.buses.map((bus, i) => (
                      <li key={`${bus.route}-${i}`}>
                        <span className="route">{bus.route}</span>
                        <span className="destination">to {bus.destination}</span>
                        <span className="eta">
                          {bus.minutes <= 0 ? "Due" : `${bus.minutes} min`}
                          {bus.live ? "" : " (timetable)"}
                        </span>
                      </li>
                    ))}
                  </ul>
                )}
              </li>
            ))}
          </ol>
          <p className="hint">Distances are in a straight line.</p>
        </section>
      )}

      <footer>
        Stops: Rapid Penang&apos;s GTFS feed on data.gov.my. Live arrivals: the Malaysia Transit API.
      </footer>
    </main>
  );
}

Bonus: ask in plain English with Supabase's MCP server

If your project is on Supabase Cloud, you can point an AI assistant at it with . Keep it read-only and scoped to one project. In Claude Code:

bash
claude mcp add --scope project --transport http supabase "https://mcp.supabase.com/mcp?project_ref=your-project-ref&read_only=true"

Then ask: “Which three bus stops are closest to Komtar, at 5.4145, 100.3296?” The assistant can answer by running the same function:

sql
select * from nearby_stops(5.4145, 100.3296);

Where to take it next

  • More cities. data.gov.my publishes GTFS feeds for other operators too, and the Malaysia Transit API covers 13 areas. Add an area column and load them all.
  • Saved stops. Let people sign in with Supabase Auth and keep favourite stops, with Row Level Security keeping each list private.
  • Live positions. The API also returns where each bus is, and Supabase Realtime could push them to every open page.

Your turn

How far is your nearest bus stop?

That's one table, one database function and one Edge Function between “where am I?” and “when's my bus?”. Start a free Supabase project, grab , load your own city's stops, and find out.

Building something bigger with Malaysian public transport data? Start with the , try the SerpApi tutorial, or read how I built Malaysia Transit without a CS degree.