Chuyển đến nội dung

Bài 28 · Rendering Modes and Functions

Gatsby Functions: Serverless API Routes

Create API endpoints in src/api with Gatsby Functions: handlers, dynamic routes, methods, JSON bodies, environment variables, CORS and form handling.

Even a mostly static site sometimes needs a bit of backend: a contact form that sends an email, a newsletter signup, a proxy that hides an API key. Gatsby Functions let you write that code in the same project. Any JavaScript or TypeScript file under src/api becomes an HTTP endpoint, deployed as a serverless function on hosts such as Netlify, Vercel or Gatsby-compatible platforms.

Your first function

JavaScript
// src/api/hello.js (real Gatsby, read-only)
export default function handler(req, res) {
  res.status(200).json({ message: "Hello from Gatsby Functions" })
}

With gatsby develop running, visit http://localhost:8000/api/hello. The path is the file path under src/api, with /api as the prefix. req and res follow the Express style: req.method, req.query, req.body, req.headers, req.cookies, and res.status(), res.json(), res.send(), res.redirect(), res.setHeader().

Routing by file name

File URL
src/api/hello.js /api/hello
src/api/users/index.js /api/users
src/api/users/[id].js /api/users/42 (req.params.id)
src/api/files/[...].js /api/files/a/b/c (req.params["0"] is a/b/c)
JavaScript
// src/api/users/[id].js (real Gatsby, read-only)
export default function handler(req, res) {
  const { id } = req.params
  if (!/^\d+$/.test(id)) {
    return res.status(400).json({ error: "id must be a number" })
  }
  res.json({ id: Number(id) })
}

Methods and bodies

A function receives every HTTP method. Check req.method and answer other methods with 405.

JavaScript
// src/api/subscribe.js (real Gatsby, read-only)
export default async function handler(req, res) {
  if (req.method !== "POST") {
    res.setHeader("Allow", "POST")
    return res.status(405).json({ error: "Use POST" })
  }
  const { email } = req.body || {}
  if (typeof email !== "string" || !email.includes("@")) {
    return res.status(400).json({ error: "A valid email is required" })
  }
  // Call your email provider here with a secret key
  const response = await fetch("https://api.example-mail.test/subscribers", {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.MAIL_API_KEY}` },
    body: JSON.stringify({ email }),
  })
  return res.status(response.ok ? 201 : 502).json({ ok: response.ok })
}

Gatsby parses JSON, URL-encoded and text bodies for you. For a webhook that needs the raw body (signature checks), export a config object to change the body parser:

JavaScript
// real Gatsby, read-only
export const config = { bodyParser: false }

Calling a function from the page

Use a relative URL so it works in development and production:

JSX
// src/components/subscribe-form.js (real Gatsby, read-only)
const [status, setStatus] = React.useState("idle")

async function onSubmit(event) {
  event.preventDefault()
  setStatus("sending")
  const res = await fetch("/api/subscribe", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email: event.target.email.value }),
  })
  setStatus(res.ok ? "done" : "error")
}

Secrets and environment variables

Functions run on the server, so they can read process.env.MAIL_API_KEY without exposing it. Variables are never prefixed GATSBY_ for secrets: that prefix is for values deliberately embedded in browser code. Set secrets in the hosting dashboard, and use a .env.development file locally (see Deploying Gatsby sites).

Limits to remember

  • Functions are short-lived: typical time limits are seconds, memory is limited, and local files you write disappear.
  • There is no shared memory between invocations; use a database or an external service for state.
  • Cold starts add latency the first time.
  • Dependencies go in package.json as usual; large ones increase the function size.

Try it: a function router

Gatsby cannot run here, so this stand-in implements the core idea: map file paths to URL patterns, then call a handler with a fake req and res.

JS Stand-in: file path to route matching

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

No output.

And the handler side with validation and status codes:

JS Stand-in: a handler with a fake req and res

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

No output.

Common mistakes

  • Putting secrets in GATSBY_ variables: they end up in public JavaScript.
  • Returning nothing: a handler that never calls res.send or res.json hangs until timeout.
  • Forgetting method checks, so a GET triggers a side effect.
  • Calling functions with an absolute localhost URL in production code.
  • Trusting input: always validate the body.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Which file creates the endpoint /api/users/42 with params.id equal to 42?

    A file named [id].js in src/api/users handles any single segment.
  2. 2. How should a function treat the wrong HTTP method?

    405 Method Not Allowed tells clients which methods are accepted.
  3. 3. Where should an email provider's secret key be read?

    Server-side env vars are not shipped to the browser.

Summary

  • Files in src/api become /api/... endpoints with an Express-like req and res.
  • [id] and [...] give dynamic and splat routes.
  • Validate input, check the method, return clear status codes.
  • Keep secrets in server-side environment variables and don't count on state between calls.

Next: Client-only routes and authentication

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.