Chrysolites Tech Academy

Ride-Hailing App Clones · Course book

Chapter 3: Ride Options, Fares and Sign-In

Pairs with Lesson 3: Ride App Clone with Next.js, Part 3

The ride app can now show a trip on a map. The final steps make it feel like a real service: drawing the actual road route, offering a choice of ride types with prices based on the journey, and requiring riders to sign in so that the app knows who they are. This chapter explains how a directions service returns a route, its distance and its duration, how a fare can be computed from them with a worked example and a graph, how a ride selector component presents the options, and how Firebase Authentication adds sign-in with a Google account, including protecting pages and showing the signed-in user. It finishes with what it takes to deploy the finished app.

Routes from a directions service

A directions API takes a list of coordinates, at least a start and an end, and returns one or more routes along real roads. Each route includes its distance in metres, its duration in seconds and its geometry, the line to draw on the map, usually as GeoJSON or as an encoded polyline. Mapbox's Directions API offers driving, walking and cycling profiles, and a driving-traffic profile that uses current traffic to estimate duration.

The confirmation page requests the route once both coordinates are known, then uses the response in two ways. The map draws the geometry as a line layer: the GeoJSON is added as a source and a layer styles it as a thick dark line, after the map's load event so the style is ready. The ride selector uses the duration and distance to show travel time and prices. A route of 1,612 seconds is 1,612 / 60 = 26.9 minutes, displayed as "27 min"; a distance of 21,300 metres is 21.3 km.

Response fieldExample valueUsed for
routes[0].distance21,300 (metres)Fare calculation, "21.3 km" label
routes[0].duration1,612 (seconds)"27 min" label, fare calculation, arrival time
routes[0].geometryA GeoJSON line of coordinatesDrawing the route on the map
waypointsThe start and end snapped to the roadPlacing markers exactly on the road
map.on("load", () => {
  map.addSource("route", { type: "geojson", data: { type: "Feature", geometry: route.geometry } });
  map.addLayer({
    id: "route-line",
    type: "line",
    source: "route",
    layout: { "line-cap": "round", "line-join": "round" },
    paint: { "line-color": "#111827", "line-width": 5 },
  });
});

Requesting the geometry as GeoJSON, with a geometries=geojson option, gives a list of coordinates that can be added directly as a source. Without that option many services return an encoded polyline, a compact text form of the same coordinates that must be decoded first. When the trip changes, the existing source's data is replaced with setData rather than adding a second layer with the same id, which would throw an error. Fitting the map to the route's own coordinates, not just the two end points, keeps a winding route fully on screen.

Arrival time is simple arithmetic: add the duration to the current time. Leaving at 14:05 with a 27-minute trip gives an arrival of 14:32. Displaying it with the browser's time formatting respects the rider's 12-hour or 24-hour preference.

Ride types and fares

Ride apps offer several categories, such as a standard car, a more comfortable one, a larger vehicle for groups and a premium option. A simple and transparent way to price them is to compute a base fare from the trip and multiply it by a factor for each category.

Worked example. Suppose a fare is a booking fee of 2.50 plus 0.90 per kilometre plus 0.30 per minute. For a trip of 21.3 km and 26 minutes, the standard fare is 2.50 + 0.90 × 21.3 + 0.30 × 26 = 2.50 + 19.17 + 7.80 = 29.47. With multipliers of 1.2 for comfort, 1.5 for a larger car and 2.0 for premium, the fares are 29.47 × 1.2 = 35.36, 29.47 × 1.5 = 44.21 and 29.47 × 2 = 58.94. Rounding to two decimal places only at the end, not after each step, avoids small rounding errors that can add up to a cent or two.
standard 37.00 larger (×1.5) 55.50 premium (×2) 74.00 0204060 0510152025 trip distance (km)fare
Figure 3.1 — Example fares by ride type, assuming city traffic of 1.6 minutes per kilometre. Multipliers make the gap between categories grow with the length of the trip.

Real services add more factors: minimum fares, airport fees, tolls, and dynamic pricing that raises prices when demand is high. Whatever the formula, compute prices on a server in a real product, because anything calculated only in the browser can be altered by the user; the browser version is for display.

The ride selector component

The ride selector sits below the map on the confirmation page. It lists the ride types from a small data array, each with a name, an image of the vehicle, the multiplier and a short note such as "Up to 6 seats". For each, it shows the travel time and the computed fare, formatted with Intl.NumberFormat so that the currency symbol and separators match the rider's locale. Tapping a row selects it, highlighted with a border, and a confirm button at the bottom shows the chosen category.

The component needs the duration from the directions response, which arrives some time after the page loads. Until then it can show the ride types with a loading placeholder in place of prices. Passing the pickup and drop-off coordinates as props, and fetching the route in an effect that depends on them, keeps the component self-contained. Handling the case where no route is found, for example between two islands with no road link, with a clear message keeps the page from showing nonsense prices.

A list where exactly one item can be chosen is, semantically, a group of radio buttons. Building the rows as labelled radio inputs, visually styled as cards, means screen readers announce "Comfort, 35.36, 2 of 4, not selected" and keyboard users can move between options with the arrow keys, all without extra code. The confirm button can then read the selected value from one piece of state, and its label can repeat the choice, for example "Choose Comfort", so the rider can see what they are about to book.

Signing in with Firebase

Firebase Authentication manages user accounts without a custom back end. The app creates a Firebase project, adds a web app to it, and copies the configuration object, which contains public identifiers, not secrets, into a firebase.js file that initialises the library. Enabling the Google provider in the Firebase console allows sign-in with a Google account.

import { getAuth, GoogleAuthProvider, signInWithPopup, onAuthStateChanged } from "firebase/auth";

const auth = getAuth(app);
const provider = new GoogleAuthProvider();

export const signIn = () => signInWithPopup(auth, provider);
export const watchUser = (callback) => onAuthStateChanged(auth, callback);

A login page shows the app's branding and a "Sign in with Google" button that calls signInWithPopup. The key function is onAuthStateChanged: it calls back with the user whenever the sign-in state changes, including once when the page loads. The home page subscribes to it in an effect: if a user is present, it stores their name and photo in state and shows them in the header; if not, it redirects to the login page with the router. Clicking the profile picture can call signOut, after which the same listener sends the rider back to the login page. The effect should return the unsubscribe function that onAuthStateChanged provides, to avoid duplicate listeners.

This client-side redirect is a convenience, not security: protecting data requires server-side checks or Firebase security rules for any database the app uses. For this project, where the pages show only public map data, a client-side check is enough to give the experience of a signed-in app.

Popups have one drawback: some mobile browsers block them or open them awkwardly. Firebase also offers signInWithRedirect, which sends the whole page to the sign-in screen and back, and many apps use it on phones and the popup on desktops. While the listener has not yet reported, the app does not know whether anyone is signed in, so showing a brief loading state, rather than flashing the login page, avoids a confusing jump for riders who are already signed in.

Deploying the app

A Next.js app deploys naturally to a hosting platform that supports it: connect the code repository, set the environment variables, such as the Mapbox token, and every push builds and publishes a new version with a public address. Two final settings matter. The Mapbox token should be restricted to the deployed address, and the deployed domain must be added to Firebase Authentication's list of authorised domains, or the Google sign-in popup will refuse to work. Testing the full flow on a real phone, signing in, searching, confirming and choosing a ride, is the last step.

Practice tasks

  1. Using the example formula, compute the standard and premium fares for a trip of 8 km and 18 minutes.
  2. A route's duration is 2,250 seconds and the rider leaves at 09:48. When do they arrive?
  3. Why should real fares be calculated on a server rather than in the browser?
  4. Explain what onAuthStateChanged does and why the effect returns its unsubscribe function.
  5. What must be added in the Firebase console before Google sign-in works on the deployed site?
  6. Describe how the ride selector should behave before the route has arrived and when no route can be found.

Install Chrysolites Tech Academy

Android / Chrome / Edge: open the browser menu and choose Install app or Add to Home screen.

iPhone / iPad (Safari): tap the Share button, then Add to Home Screen.