Skip to content

How to Create Pages With Gatsby File System Route API

Gatsby/

You can use the File System Route API to create pages from your GraphQL data. Similarly to createPages API, you choose the page path, but you don’t need to write any code. Gatsby does the underlying API calls for you.

The File System Route API is useful when you want to create a page for each node in a GraphQL collection.

Using the File System Route API

To use File System Route API, you need to create a page component in src/pages. This page serves as a template for every page that Gatsby will create for you at build-time.

The page file name must contain a special notation that differentiates it from a regular page. The notation is what enables the File System Route API.

Let’s say, you want to create pages for all your blog posts. You have a GraphQL collection named Post. The following data represents a single blog post node.

{
  title: "First Blog Post",
  author: "John Smith"
}

Create a file src/pages/{Post.title}.js.

You wrap the entire name in curly braces ({}). First comes the GraphQL type — Post. Then follows the field you want to use as the path. This creates a page with path /first-blog-post.

You can use any field from the node, Gatsby automatically creates a page for every node in the collection using the specified field.

To use a nested field for the path, you use the __ notation to point it out.

For example, to access the slug in the following nodes, name the file src/pages/{Post.fields__slug}.js

[{
  title: "First Blog Post",
  fields: {
    slug: "custom-url-for-this-post"
  }
},
{
  title: "Second Blog Post",
  fields: {
    slug: "another-custom-url"
  }
}]

In this case, Gatsby creates two pages with paths /custom-url-for-this-post and /another-custom-url.

Gatsby creates a human-readable URL from the field you specify. If your data contains any invalid characters, it removes them.

{
  fields: {
    slug: "special (symbols)!"
  }
}

In this example, Gatsby creates a page with path /special-symbols.

Querying Data Inside a Page

In the page component, you can query any data you want.

Gatsby makes the id field of the node available automatically. You can use that to get the rest of the node’s data.

query ($id: String) {
  post({id: {eq: $id}}) {
    title,
    author,
    content
  }
}

You can also access the field you specified in the file name within the query. It is available as a variable with the same name as the field.

For example, naming your file {Post.title}.js lets you access the title value from the $title variable.

query ($title: String) {
  post(title: {eq: $title}) {
    ...
  }
}

However, you should query by id because it is the fastest way.

If you want to pass your own variables to the query, you will have to use createPages API. You have no control over the pageContext using File System Route API.

References