Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 ยท Projects and Practice

Project: Portfolio Site with a Contact Function

Build a fast Gatsby portfolio: project data from JSON, optimized images, a filterable grid, and a serverless contact function with validation and spam protection.

A portfolio site is a great second project. It is small enough to finish, it needs images to look good, and it has one dynamic feature: a contact form. You will practice data from a JSON file, the image plugin, client-side filtering, and a Gatsby Function that receives form submissions safely.

Plan

Part Technique Chapter
Project list JSON data through a transformer Data layer
Screenshots GatsbyImage from queried files Images
Filter by skill Small client-side state React
Contact form Function in src/api/contact.js Functions
Head and sitemap Head API SEO

Step 1: data in JSON

Create content/projects.json and source it with gatsby-source-filesystem plus gatsby-transformer-json:

JSON
[
  { "slug": "weather-app", "title": "Weather App", "skills": ["react", "api"], "year": 2025, "screenshot": "../images/weather.png" },
  { "slug": "shop-theme", "title": "Shop Theme", "skills": ["css", "liquid"], "year": 2024, "screenshot": "../images/shop.png" }
]

Gatsby creates an allProjectsJson collection (the type name comes from the file name). Query it in the home page with gatsbyImageData for each screenshot, as in Dynamic images.

Step 2: a filterable grid

Static data is rendered at build time; filtering happens in the browser with React state. Build the page HTML for all projects, then show or hide cards by selected skill. No server request is needed, and the content is still visible to crawlers.

JSX
// real Gatsby, read-only
function Projects({ projects }) {
  const [skill, setSkill] = React.useState("all")
  const skills = ["all", ...new Set(projects.flatMap((p) => p.skills))]
  const shown = skill === "all" ? projects : projects.filter((p) => p.skills.includes(skill))
  return (
    <>
      <div role="group" aria-label="Filter by skill">
        {skills.map((s) => (
          <button key={s} aria-pressed={s === skill} onClick={() => setSkill(s)}>{s}</button>
        ))}
      </div>
      <ul>{shown.map((p) => <li key={p.slug}>{p.title}</li>)}</ul>
    </>
  )
}

The filter logic is plain JavaScript, so you can test it here:

JS Stand-in: skill filter and sorting

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

No output.

Step 3: the contact function

The form posts JSON to /api/contact. The function must be defensive: it is a public endpoint that anyone (including bots) can call.

JavaScript
// src/api/contact.js (real Gatsby, read-only)
const MAX = { name: 80, email: 120, message: 2000 }

export default async function handler(req, res) {
  if (req.method !== "POST") {
    res.setHeader("Allow", "POST")
    return res.status(405).json({ error: "Use POST" })
  }
  const { name, email, message, website } = req.body || {}

  if (website) return res.status(200).json({ ok: true })        // honeypot: bots fill hidden fields

  const errors = {}
  if (typeof name !== "string" || !name.trim() || name.length > MAX.name) errors.name = "Name is required"
  if (typeof email !== "string" || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email) || email.length > MAX.email) errors.email = "Valid email required"
  if (typeof message !== "string" || message.trim().length < 10 || message.length > MAX.message) errors.message = "Message must be 10-2000 characters"
  if (Object.keys(errors).length) return res.status(400).json({ errors })

  const response = await fetch(process.env.MAIL_ENDPOINT, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.MAIL_API_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ to: process.env.CONTACT_TO, subject: `Portfolio message from ${name}`, text: `${email}\n\n${message}` }),
  })
  return res.status(response.ok ? 200 : 502).json({ ok: response.ok })
}

Notes: validate on the server even if the form validates in the browser; limit lengths; keep secrets in unprefixed environment variables; use a honeypot field (hidden input) to catch simple bots, and add rate limiting or a CAPTCHA service if spam grows. Be careful with header injection: never put user input into email headers, only into the body, as the code does (the subject contains the name, so a mail library that rejects newlines is required, or strip them).

Test the validation logic here, using the same function body with a fake req and res:

JS Stand-in: validate contact submissions

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

No output.

Step 4: the form

On the client, disable the button while sending, show field errors from the errors object, and give the user a confirmation. Use real <label> elements and associate error messages with aria-describedby so the form is accessible. Keep the hidden honeypot input out of the tab order (tabIndex={-1}, autoComplete="off", hidden with CSS, not type="hidden").

Step 5: finish

  • Add Head to each page with a unique title and description.
  • Use loading="eager" for the first screenshot only.
  • Add rel="noopener" to external links that open in a new tab.
  • Deploy to a host with Functions support (see Deploying) and set MAIL_API_KEY, MAIL_ENDPOINT and CONTACT_TO there.
  • Send a test message in production and check the spam folder.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why must the contact function validate data when the form already does?

    Client-side checks are conveniences, not security.
  2. 2. What does a honeypot field do?

    A filled honeypot indicates an automated submission.
  3. 3. Where should MAIL_API_KEY live?

    Server-only variables never reach the browser.

Summary

  • Source JSON with a transformer, query screenshots with gatsbyImageData, filter in React state.
  • Contact forms need a serverless function that checks the method, validates, limits sizes and keeps secrets server-side.
  • Use a honeypot, and add rate limiting if abused; keep user input out of email headers.
  • Provide accessible labels and error messages.

Next: Practice: a Gatsby review