challenges

Next.js Data Fetching: Part 1 (Solution)

You can find a summary of the code updates in this pull request . Read on for explanations.

1. Create the route.ts file

We need to create a route handler : an endpoint that can be contacted via HTTP. In the next workshop in this series, we’ll contact this route handler from the client side.

The goal is to call the endpoint api/get-quote-styles for this route handler. That means we need to create a file here: src/app/api/get-quote-styles/route.ts. (A note on the endpoint name: we’re only getting a random quote for now; the “style” will come in the next series).

2. Create a GET function

This route handler will handle GET requests, so we’ll name the function GET .

route.ts

export function GET() {
  
}

3. Get random quote

The function will return a random quote. We’ll get the random quote using the (conveniently named) getRandomQuote function from src/helpers/random-quotes.ts:

route.ts

import { getRandomQuote } from "@/helpers/random-quotes";
 
export function GET() {
  const generatedQuote = getRandomQuote();
}

4. Return JSON

Eventually (in the next series), we’re going to return a more complicated response than just a quote, so we’ll need to structure the response using JSON . However, even if we’re only returning a quote, it’s still useful to return JSON. JSON helps determine on the client end whether the response is valid – if we’re looking for a property in the response and it’s not there, chances are something went wrong.

We’ll use the NextResponse.json method to return the JSON.

route.ts

import { NextResponse } from "next/server";
 
export function GET() {
  const generatedQuote = getRandomQuote();
 
  return NextResponse.json({ quote: generatedQuote });
}

5. Access the route handler

Let’s see what we’ve got. To access the endpoint:

  1. Run npm run dev from the top level of the app in the terminal.
  2. Access http://localhost:3000/api/get-quote-styles to hit the endpoint and see the result in your browser. Since you’re retrieving a random quote, the response should be different every time you refresh this page.

The page in the browser will be raw JSON, something like this (your quote will probably differ since it’s randomly selected!):

a JSON response with a 'quote' property and a text value

We’ll take care of those grammatical errors in the next series (AI Style Generator). 😁

Up next

In the next workshop, we’ll fetch data from this endpoint and display it in the UI.