Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 36 ยท Projects and Practice

Practice: Gatsby Exercises and Review

Sharpen your Gatsby skills with runnable exercises on slugs, pagination, image widths and redirects, a debugging checklist, and interview-style review questions.

You have seen sourcing, GraphQL, images, Markdown, rendering modes, Functions and deployment. This final lesson is for practice. It contains small exercises that you can run and edit, a debugging checklist for the errors beginners meet most, and review questions. Try each exercise before reading the hint, then compare.

Exercise 1: slug from a file path

createFilePath turns file paths into URLs. Write your own: lowercase, remove index.md and the extension, make folder separators into slashes, and ensure a leading and trailing slash.

JS Exercise 1: write slugFromPath

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Hint: strip the content/posts/ prefix, remove /index.md or .md, replace non-alphanumerics with hyphens, then add the prefix and slashes. A sample solution:

JavaScript
function slugFromPath(path) {
  const name = path
    .replace(/^content\/posts\//, "")
    .replace(/(\/index)?\.md$/, "")
    .toLowerCase()
    .replace(/[^a-z0-9/]+/g, "-")
    .replace(/^-|-$/g, "")
  return `/blog/${name}/`
}

Exercise 2: previous and next with sorting

Given unsorted posts, sort by date (newest first) and return each post's neighbors. Remember the first has no previous and the last no next.

JS Exercise 2: neighbors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Hint: sort a copy, then map with the index, using list[i - 1]?.id ?? null.

Exercise 3: choose image widths

Given a source width, a display width and the layout, return the list of generated widths. Use 1x and 2x densities, never upscale, and for fullWidth use the breakpoints [750, 1080, 1366, 1920].

JS Exercise 3: image widths

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Hint: build the list, filter w <= source, remove duplicates. For constrained at 600 from a 900 source, the 2x width of 1200 exceeds the source and is dropped.

Exercise 4: redirect or not

Decide the HTTP status for each request path: 301 for known moved pages, 200 for existing ones and 404 for everything else.

JS Exercise 4: status for a URL

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Hint: check pages.has(path) first, then moved[path], else 404. Never answer 200 for a missing page.

Debugging checklist

Symptom Likely cause Fix
Cannot query field "x" on type "Y" Field missing from every node Declare it in createSchemaCustomization, or check front matter spelling
window is not defined during build Browser API used during render Use useEffect or a typeof window check
Page shows the same content for every URL Missing context ids Pass the id to createPage and use $id in the query
Image is blank getImage returned undefined Handle the missing case and check the relative path
Site works locally, blank page on GitHub Pages No path prefix pathPrefix and gatsby build --prefix-paths
Change not visible after editing gatsby-node.js Dev server needs a restart Stop and run gatsby develop again; if odd, gatsby clean
Hydration mismatch warnings Server and client HTML differ Move random or time-dependent output into useEffect
Build runs out of memory Too many or too big images Raise NODE_OPTIONS=--max-old-space-size, resize sources

When something is mysterious, use the GraphiQL explorer at localhost:8000/___graphql to see the real data, run gatsby clean, and read the first error message in the terminal, because the later ones are often consequences.

Review questions

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A product page must show the visitor's saved cart. Which approach fits?

    Per-user data cannot be baked into shared static HTML.
  2. 2. Your build is slow because of 15,000 old product pages that get little traffic. What helps most?

    DSG builds those pages on first request instead of at build time.
  3. 3. Which pairing is correct?

    StaticImage props must be literals, GATSBY_ values are public, and getServerData belongs to a page component.
  4. 4. What makes a good production checklist item?

    gatsby serve reveals build-only problems.
  5. 5. Why should a function ignore requests where the honeypot field is filled?

    Humans never see the hidden input.

Where to go next

  • Rebuild the blog project with MDX and a few interactive components.
  • Add a search index to it, loaded after the first interaction.
  • Source content from a headless CMS with a source plugin and compare build times.
  • Try a rendering-mode experiment: one SSG page, one DSG, one SSR, and record how each behaves on your host.
  • Read the other tracks for the tools around Gatsby: React, JavaScript and GraphQL-style APIs.

Summary

  • Practice the pure-logic parts (slugs, pagination, image widths, redirect decisions) until they are second nature; they are most of gatsby-node.js.
  • Use a checklist when debugging: schema, context, browser-only code, prefixes, restart and clean.
  • Choose the rendering mode by data freshness and page count.
  • Keep secrets out of the browser, validate on the server and preview production builds.

Back to the course overview: Gatsby