DEV Community

Cover image for Build a Cheapest Flight Date Finder with Next.js and SearchApi
Arindam Majumder
Arindam Majumder Subscriber

Posted on Edited on Originally published at arindamm.dev

Build a Cheapest Flight Date Finder with Next.js and SearchApi

Flight booking sites make it rigid when you want to take a trip: you’ve got to pick a date. Sometimes, you don’t know exactly when you want to fly, but you have a timeframe in mind. Finding the cheapest day to fly within your timeframe would require you to manually check every route combination, which can be time-consuming.

This article teaches you how to build a cheapest-fly-date-finder using Next.js and SearchApi. The app takes a route, a departure window, and a trip duration to find round-trip date pairs ranked by price using the SearchApi’s Google Flights Calendar API.

For example, say you want to fly from New York to London any day between the 1st and 7th of November and stay for 7 days; the app returns the cheapest round-trip pair within your departure window (6th - 13th Nov at $692 at the time of writing this article).

Try out the tool here.The full code is on GitHub.

Prerequisites

  • Basic familiarity with JavaScript or TypeScript and Next.js.
  • Node.js (v 20.9.0 or later) and npm are installed on your local machine.
  • A SearchApi account and API key. If you don’t have one, create a free account and get 100 free searches.

Set up the project and add your SearchApi key

Clone the repo and install dependencies:

git clone https://github.com/Studio1HQ/cheapest-fly-date-finder.git
cd cheapest-fly-date-finder/frontend
npm install
Enter fullscreen mode Exit fullscreen mode

Create your .env file and add your API key:

SEARCHAPI_API_KEY=your_key_here
Enter fullscreen mode Exit fullscreen mode

Run npm run dev and open http://localhost:3000 to confirm the search form loads.

A quick look at the architecture

The app is a Next.js app with a form and 2 API routes that call SearchApi: api/location and api/calendar. Form handling, autocomplete interactions, and showing of results are handled client-side while the routes communicate with SearchApi on the backend.

As a user types the name of their location(s), requests are made to the Flights Location Search API to fetch cities and airport suggestions. When the user submits the form, the departure window, locations (route), and trip duration are sent to the SearchApi Flights Calendar API through the api/calendar route. The route filters and ranks the returned fare combinations before sending it to the client.

This design replaces one search per date pair with a single calendar request.

Architecture of the cheapest-day-to-fly finder: browser components call two Next.js API routes, which call SearchApi’s location and Flights Calendar endpoints

In the codebase, LocationAutocomplete.tsx and SearchForm.tsx handle the search inputs. CheapestDayFinder.tsx connects form submission to the calendar search, while the location route and calendar route make the server-side provider calls. ResultsPanel.tsx and FareRow.tsx present the search outcome.

The rest of the article follows that flow: Stage One collects the travel details, Stage Two turns them into a Calendar API request, and Stage Three transforms the returned calendar data into ranked results.

The Live tool

Image2

Stage 1: Build the search form with city and airport autocomplete

Stage One builds a search form that collects four inputs: origin, destination, departure window, and trip duration. The Flights API identifies airports and cities by IATA codes (unique three-letter codes, such as JFK), which most travelers don’t know, so the form uses SearchApi’s Google Flights Location Search API to power an autocomplete that accepts city or airport names.

Making location search responsive

The LocationAutocomplete component fetches location suggestions after the user types at least 2 characters. It waits 300ms before making the request to avoid unnecessary API calls as the user types.

const query = value.trim();

if (query.length < 2 || isManualSelectionRef.current) {
  isManualSelectionRef.current = false;
  return;
}

const controller = new AbortController();

const timer = setTimeout(async () => {
  setIsLoading(true);
  try {
    const res = await fetch("/api/location", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ query, departure }),
      signal: controller.signal,
    });

    if (!res.ok) throw new Error("Location fetch failed");
    const data = await res.json();
    const results: LocationItem[] = data.locations || [];

    setLocations(results);
    setIsOpen(results.length > 0);
  } catch (err: unknown) {
    if ((err as Error).name !== "AbortError") {
      console.error("Failed to fetch location suggestions:", err);
    }
  } finally {
    setIsLoading(false);
  }
}, 300);

return () => {
  clearTimeout(timer);
  controller.abort();
};
Enter fullscreen mode Exit fullscreen mode

The AbortController cancels the previous request when the effect is cleaned up.

Once suggestions arrive, the dropdown presents city results and airports listed under each city, if they’re available.

Users can select either level. A city selection stores its short or full name; an airport selection stores a city label with its airport code when one is available.

const selectCity = (city: LocationItem) => {
  isManualSelectionRef.current = true;
  onChange(city.short_name || city.full_name);
  setLocations([]);
  setIsOpen(false);
};

const selectAirport = (airport: AirportItem, city: LocationItem) => {
  isManualSelectionRef.current = true;
  const text = airport.airport_code
    ? `${city.short_name || airport.title} (${airport.airport_code})`
    : airport.title;
  onChange(text);
  setLocations([]);
  setIsOpen(false);
};
Enter fullscreen mode Exit fullscreen mode

The selection handlers allow users to choose a broad city result or a specific airport from the same field. The form passes departure={true} for the origin and departure={false} for the destination, which determines the search type used by the location route.

The manual-selection flag prevents the selected value from sending another autocomplete API request.

Creating the location API route

The autocomplete component sends the autocomplete queries to the api/location route.

export const POST = async (request: Request) => {
  const { query, departure } = await request.json();
  if (!query) {
    return NextResponse.json({ error: "No query provided" }, { status: 400 });
  }

  const url = "https://www.searchapi.org/api/v1/search";
  const params = new URLSearchParams({
    engine: "google_flights_location_search",
    q: query,
    api_key: process.env.SEARCHAPI_API_KEY!,
    search_type: departure ? "departure" : "arrival",
  });

  try {
    const response = await fetch(`${url}?${params}`);
    const data = await response.json();
    if (!data) {
      return NextResponse.json({ error: "No location data found" }, { status: 404 });
    }
    return NextResponse.json(data);
  } catch (error) {
    console.error("Error is: ", error);
    return NextResponse.json(
      { error: "Failed to fetch location data" },
      { status: 500 }
    );
  }
};
Enter fullscreen mode Exit fullscreen mode

The route accepts the query and the departure flag, then passes them to SearchApi as q and search_type. It parses the provider response and returns that data to the autocomplete component, which reads its locations field.

Setting the departure window and duration

The form also needs to collect the time between when the user wants to depart and how long they intend to stay. You use date fields and number inputs to collect the data. This data determines the date combinations the app should compare.

The SearchForm component validates the form inputs and passes them in FareSearchQuery to the onSearch callback:

export default function SearchForm({ onSearch, isSearching }: SearchFormProps) {
  const [query, setQuery] = useState<FareSearchQuery>(DEFAULT_QUERY);
  const [errors, setErrors] = useState<FormErrors>({});

  // ...

  const validate = (): FormErrors => {
    const next: FormErrors = {};
    const from = query.from.trim();
    const to = query.to.trim();

    if (!from) next.from = "Enter an origin city or airport.";
    if (!to) next.to = "Enter a destination city or airport.";
    if (from && to && normalizeLocation(from) === normalizeLocation(to)) {
      next.to = "Destination must differ from the origin.";
    }

    if (!query.departAfter) next.departAfter = "Pick earliest departure date.";
    if (!query.departBefore) next.departBefore = "Pick latest departure date.";

    if (query.departAfter && query.departBefore) {
      if (query.departBefore < query.departAfter) {
        next.departBefore = "Latest date must be on or after earliest date.";
      } else if (dayDiff(query.departAfter, query.departBefore) > 31) {
        next.departBefore = "Departure window cannot exceed 30 days.";
      }
    }

    const duration = Number(query.durationDays);
    if (!duration || duration < 1 || duration > 60) {
      next.durationDays = "Trip duration must be 1–60 days.";
    }

    return next;
  };

  // ...
}
Enter fullscreen mode Exit fullscreen mode

The function checks:

  • If the locations and dates are present
  • That the locations differ
  • That the departure dates are in order, and
  • That the duration is an integer from 1 to 60

In the form’s JSX, the autocomplete fields and date/duration inputs update the same query state:

// Inside SearchForm's return statement...

<LocationAutocomplete
  id="search-from"
  label="Origin"
  value={query.from}
  onChange={setValue("from")}
  placeholder="JFK or New York"
  error={errors.from}
  departure={true}
/>

<LocationAutocomplete
  id="search-to"
  label="Destination"
  value={query.to}
  onChange={setValue("to")}
  placeholder="LHR or London"
  error={errors.to}
  departure={false}
/>

<Field
  id="search-depart-after"
  label="Earliest departure"
  type="date"
  value={query.departAfter}
  onChange={setValue("departAfter")}
  error={errors.departAfter}
/>

<Field
  id="search-depart-before"
  label="Latest departure"
  type="date"
  value={query.departBefore}
  onChange={setValue("departBefore")}
  error={errors.departBefore}
/>

<Field
  id="search-duration"
  label="Length of stay (days)"
  type="number"
  min={1}
  max={60}
  value={query.durationDays ? String(query.durationDays) : ""}
  onChange={(val) => {
    const num = val === "" ? 0 : Number(val);
    setValue("durationDays")(num);
  }}
  placeholder="7"
  error={errors.durationDays}
/>
Enter fullscreen mode Exit fullscreen mode

The departure flag in the LocationAutocomplete component tells the autocomplete whether the search is for departure or arrival. The date fields capture the time window the user has to fly, and the duration is how long they’ll stay before returning.

On successful validation, the submit handler sends the trimmed locations, date value, and duration to the onSearch callback.

Connecting the inputs to the next stage

The CheapestDayFinder component receives the query through the onSearch callback of SearchForm. It stores the query, extracts the airport codes where it can, and sends the search details to the api/calendar route.

Inside CheapestDayFinder, runSearch converts the form query into the calendar route’s request body:

export default function CheapestDayFinder() {
  const [status, setStatus] = useState<SearchStatus>("idle");
  const [results, setResults] = useState<FlightFare[]>([]);
  const [activeQuery, setActiveQuery] = useState<FareSearchQuery | null>(null);

  // ...

  const runSearch = useCallback(async (query: FareSearchQuery) => {
    const id = ++requestId.current;
    setActiveQuery(query);
    setStatus("loading");
    setResults([]);

    // ...

    const originCode = extractAirportCode(query.from);
    const destinationCode = extractAirportCode(query.to);

    const response = await fetch("/api/calendar", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        origin: originCode,
        destination: destinationCode,
        departAfter: query.departAfter,
        departBefore: query.departBefore,
        durationDays: query.durationDays,
      }),
    });

    // ...
  }, []);

  // ...
}
Enter fullscreen mode Exit fullscreen mode

For a selected airport such as New York (JFK), extractAirportCode sends JFK. The request carries the route, departure window, and stay length to the api/calendar route.

The requestId ref in runSearch (const id = ++requestId.current) prevents an older response from overwriting state after a newer request has begun.

extractAirportCode extracts the three-letter unique identifier of an airport or city:

export function extractAirportCode(location: string): string {
  // 1. Matches "(LHR)" in "London (LHR)"
  const match = location.match(/\(([A-Za-z]{3})\)/);
  if (match) {
    return match[1].toUpperCase();
  }

  // 2. If the user typed a 3-letter code directly (e.g. "LHR" or "lhr")
  const trimmed = location.trim();
  if (/^[A-Za-z]{3}$/.test(trimmed)) {
    return trimmed.toUpperCase();
  }

  // 3. Fallback to the original value if no code found (e.g. city name)
  return trimmed;
}
Enter fullscreen mode Exit fullscreen mode

At this point, the form has turned a traveler’s flexible plans into structured search input. In Stage Two, the app uses these values to construct and send a request to SearchApi’s Google Flights Calendar API.

Stage 2: Query the Google Flights Calendar API from a Next.js route

The app sends one request to SearchApi’s Google Flights Calendar API for the whole departure window, and the api/calendar route turns the returned fare combinations into a ranked list.

Preparing the calendar search

The api/calendar route checks the request body for non-empty dates and locations before calling the Flights Calendar API. The check also ensures the user’s departure timeframe is not longer than 30 because of date combination limits.

The checks happen in the top part of the route before you build the provider request:

export const POST = async (request: Request) => {
  try {
    const body = await request.json();
    const { origin, destination, departAfter, departBefore, durationDays } = body;

    if (!origin || !destination || !departAfter || !departBefore) {
      return NextResponse.json(
        { error: "Origin, destination, and departure dates are required." },
        { status: 400 }
      );
    }

    const duration = Number(durationDays);
    if (!Number.isInteger(duration) || duration < 1 || duration > 60) {
      return NextResponse.json(
        { error: "Trip duration must be an integer between 1 and 60 days." },
        { status: 400 }
      );
    }

    // ...

    const apiKey = process.env.SEARCHAPI_API_KEY;
    if (!apiKey) {
      return NextResponse.json(
        { error: "SEARCHAPI_API_KEY is not configured on the server." },
        { status: 500 }
      );
    }

    // ...
  } catch (error) {
    // ...
  }
};
Enter fullscreen mode Exit fullscreen mode

The route returns a client error for invalid inputs and a server error if the API key isn’t configured.

Constructing the outbound and return date ranges

The route uses the trip duration input to shift both ends of the departure window, creating the corresponding return-date window.

The date calculations and query parameters in the calendar route show how the app expresses that search to SearchApi:

// Inside the POST handler, after validating the request...

const outboundStart = departAfter;
const outboundEnd = departBefore;
const returnStart = addDays(departAfter, duration);
const returnEnd = addDays(departBefore, duration);

const url = "https://www.searchapi.org/api/v1/search";
const params = new URLSearchParams({
  engine: "google_flights_calendar",
  flight_type: "round_trip",
  departure_id: origin,
  arrival_id: destination,
  outbound_date: outboundStart,
  return_date: returnStart,
  outbound_date_start: outboundStart,
  outbound_date_end: outboundEnd,
  return_date_start: returnStart,
  return_date_end: returnEnd,
  currency: "USD",
  hl: "en",
  gl: "us",
  api_key: apiKey,
});

// ...
Enter fullscreen mode Exit fullscreen mode

The request selects SearchApi’s google_flights_calendar as the engine to retrieve the flights data and specifies the flight_type as a round trip. The request sets flight_type to round_trip so each calendar entry includes a return date. Round trip is the default, so this makes the intent explicit.

The request includes both the start/end bounds for each date range and the outbound_date and return_date parameters, which are set to the start dates. The request also sets currency to USD, hl to en, and gl to us.

addDays adds the trip duration to the dates of the departure window:

export function addDays(isoDate: string, days: number): string {
  const d = parseIsoDate(isoDate);
  d.setUTCDate(d.getUTCDate() + days);
  return d.toISOString().slice(0, 10);
}
Enter fullscreen mode Exit fullscreen mode

Making the request and handling provider errors

After creating the query, the route fetches the Flights Calendar API response. It handles non-success HTTP responses separately from a provider error returned in a successfully parsed response. One specific provider error (exceeding its unique-combination limit) is returned with a message asking the user to narrow the departure range.

If you set a departure window that produces too many date combinations, the Flights Calendar API returns an error that ends like this:

... results in 400 unique combinations. This exceeds the maximum allowed limit of 200 combinations.
Enter fullscreen mode Exit fullscreen mode

Every outbound date pairs with every return date, so two 20-day windows produce 20 × 20 = 400 combinations. The route catches this error and returns “Narrow your departure date range” so the traveler can narrow the window to 14 days or fewer.

The fetch and error handling in the route determine whether calendar data can be used:

// After constructing `url` and `params`...

const response = await fetch(`${url}?${params}`);
if (!response.ok) {
  const errorText = await response.text();
  console.error("SearchApi Calendar request failed:", response.status, errorText);

  const isCombinationLimit =
    response.status === 400 &&
    errorText.includes("unique combinations") &&
    errorText.includes("maximum allowed limit");

  if (isCombinationLimit) {
    return NextResponse.json(
      {
        errorTitle: "Narrow your departure date range",
        error:
          "This search creates too many date combinations for the flight provider. Choose a shorter departure window and try again.",
      },
      { status: 400 }
    );
  }

  return NextResponse.json(
    { error: "Failed to fetch fares from flight provider." },
    { status: response.status }
  );
}

// ...
Enter fullscreen mode Exit fullscreen mode

The response message for the combination-limit error is more actionable and prompts the user to narrow their departure range. Other unsuccessful responses are logged and returned as provider-request failures. The client controller reads the route’s JSON response and moves the search into an error state if the response is unsuccessful or contains an error field.

Extracting the calendar entries

On a successful HTTP response, the route parses the JSON using the SearchApiCalendarResponse type. It checks for a provider-level error, then retrieves the calendar array. If the response doesn’t contain an array there, the route uses an empty array.

The response parsing and calendar extraction establish the handoff to fare processing:

const data: SearchApiCalendarResponse = await response.json();
if (data.error) {
  console.error("SearchApi returned error:", data.error);
  return NextResponse.json(
    { error: data.error },
    { status: 502 }
  );
}

const calendarItems: SearchApiCalendarItem[] = Array.isArray(data.calendar)
  ? data.calendar
  : [];

// The calendar entries are processed below...
Enter fullscreen mode Exit fullscreen mode

The types for the provider response and each calendar entry are defined in frontend/src/lib/types.ts in the repo.

A calendar item may include a departure date, return date, price, and flags such as has_no_flights. Those raw entries are the input to Stage Three, where the route filters out unusable combinations, applies the requested duration, ranks fares, and returns the results for display.

Stage 3: Rank the cheapest round-trip date pairs

The Flights Calendar API returns date combinations, but not every one of the combinations is usable to the user. This section filters those combinations, converts them into the app’s FlightFare format, ranks them by price, and renders the lowest fare first.

Filtering calendar entries and matching trip duration

The calendar route filters out entries that have no departure or return dates, are marked as having no flights, and/or have a non-positive numeric fare. It also checks each remaining pair against the trip duration.

Inside the calendar route, this filter keeps only entries with the requested duration:

api/calendar/route.ts:

// Inside the POST handler, after extracting `data.calendar`...

const validFares: FlightFare[] = calendarItems
  .filter((item): item is Required<Pick<
    SearchApiCalendarItem,
    "departure" | "return" | "price"
  >> => {
    if (!item.departure || !item.return) return false;
    if (item.has_no_flights) return false;
    if (typeof item.price !== "number" || item.price <= 0) return false;

    const tripLength = dayDiff(item.departure, item.return);
    return tripLength === duration;
  })

// ...
Enter fullscreen mode Exit fullscreen mode

dayDiff uses UTC date arithmetic, so the duration comparison operates on calendar dates without local-time shifts:

export function dayDiff(startIso: string, endIso: string): number {
  const s = parseIsoDate(startIso);
  const e = parseIsoDate(endIso);
  const diffMs = e.getTime() - s.getTime();
  return Math.round(diffMs / (1000 * 60 * 60 * 24));
}
Enter fullscreen mode Exit fullscreen mode

Applying this check to each pair ensures the displayed options fit the stay length the traveler requested.

Normalizing and ranking the fares

The route sorts the remaining entries by the cheapest. It maps the entries to the FlightFare shape the frontend expects. Each entry contans the route codes, departure and return dates, price (USD), and a Google Flights link in case a user wants to take a look at the listing.

frontend/src/app/api/calendar/route.ts:

// Continuing the `validFares` pipeline...

.sort((a, b) => a.price - b.price)
.map((item, index) => {
  const inspectUrl = `https://www.google.com/travel/flights?q=Flights%20to%20${encodeURIComponent(
    destination
  )}%20from%20${encodeURIComponent(origin)}%20on%20${item.departure}%20through%20${item.return}`;

  return {
    id: `${origin}-${destination}-${item.departure}-${item.return}-${index}`,
    fromCode: origin,
    toCode: destination,
    fromCity: origin,
    toCity: destination,
    date: item.departure,
    returnDate: item.return,
    priceUsd: item.price,
    airline: null,
    durationMinutes: null,
    stops: null,
    inspectUrl,
  };
});

return NextResponse.json({
  fares: validFares,
  totalFound: validFares.length,
  requestedDuration: duration,
});
Enter fullscreen mode Exit fullscreen mode

By sorting first, you put the cheapest fare at index 0. The route then returns the ranked fares alongside the count and requested duration. Airline, flight duration, and stop-count fields are included in the normalized shape, but are set to null here because you don’t need them for this project.

Showing the cheapest option

The ResultsPanel renders the returned fares, passing the isCheapest flag to the first item. The flag is used in the UI to designate the cheapest fare combination so it stands out from the other combinations.

Each row shows the dates, round-trip price, and a link to inspect the fare on Google Flights.

frontend/src/components/ResultsPanel.tsx:

// Inside ResultsPanel's successful-results branch...

{status === "success" && results.length > 0 && query ? (
  <>
    <ResultsHeading query={query} count={results.length} />
    <ol className="mt-3 space-y-2.5">
      {results.map((fare, index) => (
        <FareRow key={fare.id} fare={fare} isCheapest={index === 0} />
      ))}
    </ol>
  </>
) : null}
Enter fullscreen mode Exit fullscreen mode

Because the server already sorts the fares, the first row is the lowest-priced fare. FareRow uses that flag to show its “Lowest fare” label and accent styling.

Handling loading, empty, and error states

The results area shows the state of the search. The results area shows a four row-shaped skeletons when the request is in progress. And if a request is successful but no fares are returned, the results area UI explains that no matching flights were found for the user’s inputs.

If the request fails completely, the results area shows an error panel with a retry button.

The loading, empty, and error branches in ResultsPanel make those outcomes visible to the traveler:

frontend/src/components/ResultsPanel.tsx:

// Inside ResultsPanel's return statement...

{status === "loading" ? (
  <>
    <p role="status" className="sr-only">
      Searching flight calendar fares…
    </p>
    {query ? <ResultsHeading query={query} /> : null}
    <ol className="mt-3 space-y-2.5">
      {Array.from({ length: 4 }, (_, index) => (
        <FareRowSkeleton key={index} />
      ))}
    </ol>
  </>
) : null}

{status === "error" ? (
  <StatePanel
    tone="alert"
    icon={<AlertTriangleIcon className="size-6" />}
    title={errorTitle ?? "We could not load flight fares"}
    action={
      <Button variant="quiet" onClick={onRetry} className="mt-2">
        Try search again
      </Button>
    }
  >
    {errorMessage ?? "Something went wrong while querying Google Flights. Please try again."}
  </StatePanel>
) : null}

{status === "success" && results.length === 0 ? (
  <StatePanel
    icon={<CalendarIcon className="size-6" />}
    title="No flights found for this window"
  >
    {/* The panel describes the searched route, dates, and duration. */}
    ...
  </StatePanel>
) : null}
Enter fullscreen mode Exit fullscreen mode

The skeleton, empty, and error states distinguish “still searching,” “no matching dates,” and “the search failed” rather than leaving the results area blank. The error panel’s retry action calls back into the controller, which reruns the active query.

Bringing the three stages together

Here’s the finished flow:

A user’s inputs (route, departure window, and trip duration) are collected and sent to the api/calendar API route to get round-trip fare combinations. The returned date pairs are sorted by price in an ascending order.

Users can inspect each listing on Google Flights.

The UI shows the progress of a request and tells the user when there are no available fares or when a search fails.

Here’s a real run for a user who wants to travel to Manchester from San Francisco between the 1st and 7th of November and stay for 10 days:

demo

“07 Nov – 17 Nov” at $798 is the cheapest option.

6. Conclusion: Making flexible travel dates easier to compare

The Cheapest-Day-to-Fly Finder turns flexible travel plans into a ranked set of round-trip pairs. Users enter a route, a departure window, and a trip duration; the app uses SearchApi’s Google Flights Location Search and Calendar endpoints to find matching fare combinations, then sorts them by price.

The app’s main idea is to make it easy to find cheap flight options when you aren't sure of exactly when to travel. So, you no longer have to manually check every possible flight date; with only a few inputs, you get sorted round-trip pairs.

You can't use the app to book a flight, though. It's for narrowing your search. For each round-trip pair, there's a link to inspect it on Google Flights.

Run the finder on your own route and compare the lowest fare with what Google Flights shows. You can create a free SearchApi account to get 100 free searches.

Top comments (0)