Shopify Hydrogen is Shopify’s React-based framework tailored for building fast and dynamic custom storefronts. One of Hydrogen’s most powerful features is its native support for serverless functions, which allow developers to run backend logic without setting up a dedicated server infrastructure. Serverless functions not only simplify development but also scale effortlessly with demand, making them ideal for modern commerce applications.

In this blog, we’ll explore how serverless functions work in Hydrogen, how to build and deploy them, and best practices for leveraging them in Shopify storefronts.

What Are Serverless Functions in Hydrogen?

Serverless functions in Hydrogen are backend API endpoints that live alongside your frontend code. These are API routes that you define inside the /src/routes/api/ folder, and they’re powered by Vite’s server API conventions. When deployed to Shopify’s Oxygen hosting platform (or to other serverless environments like Netlify or Vercel), these functions respond to HTTP requests and can perform tasks such as:

  • Fetching data from third-party APIs
  • Processing custom checkout logic
  • Performing authentication
  • Handling form submissions
  • Working with Shopify’s Admin or Storefront APIs securely

Why Use Serverless Functions in Hydrogen?

  • No infrastructure to manage
    Functions run on demand, scaling automatically.
  • Secure handling of sensitive logic
    Store secret keys and perform logic like checkout manipulation without exposing it to the frontend.
  • Faster page loads
    Offload non-critical operations to async backend functions.
  • Seamless integration
    Serverless routes are treated as native endpoints within Hydrogen.

Folder Structure & Setup

To define a serverless function in Hydrogen, follow this structure:

/src/routes/api/hello-world.server.js

The file exports a loader function which handles GET requests.

// src/routes/api/hello-world.server.js

export async function loader({request}) {
  return new Response(JSON.stringify({message: 'Hello from serverless!'}), {
    headers: {'Content-Type': 'application/json'},
  });
}

This endpoint becomes available at:

/api/hello-world

You can also handle POST requests by exporting an action function.

Example Use Case: Securely Fetching Customer Orders

Let’s say you want to fetch a customer’s order history using the Storefront API. You’d want to keep the Storefront access token private.

// src/routes/api/orders.server.js

export async function loader({request}) {
  const customerAccessToken = new URL(request.url).searchParams.get('token');

  const res = await fetch('https://your-shopify-store.myshopify.com/api/2024-04/graphql.json', {
    method: 'POST',
    headers: {
      'X-Shopify-Storefront-Access-Token': process.env.SHOPIFY_STOREFRONT_API_TOKEN,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: `
        query ($token: String!) {
          customer(customerAccessToken: $token) {
            orders(first: 10) {
              edges {
                node {
                  id
                  name
                  totalPrice {
                    amount
                    currencyCode
                  }
                }
              }
            }
          }
        }
      `,
      variables: {token: customerAccessToken},
    }),
  });

  const data = await res.json();
  return new Response(JSON.stringify(data), {
    headers: {'Content-Type': 'application/json'},
  });
}

Now you can call this endpoint securely from the frontend.

Using Environment Variables

Serverless functions can access environment variables by adding them in your .env file:

SHOPIFY_STOREFRONT_API_TOKEN=your-secure-token

And then access it in your function using process.env.

Make sure to prefix your public environment variables with PUBLIC_ if you want them exposed to the frontend. Otherwise, keep them private for server-side use only.

Deployment Notes (Oxygen / Vercel / Netlify)

  • Shopify Oxygen: Serverless functions are automatically deployed and routed with your Hydrogen app.
  • Netlify: Functions are picked up from netlify/functions or can be bundled with Hydrogen using Netlify’s adapter.
  • Vercel: Use the Vercel Hydrogen adapter to integrate your serverless functions as Vercel API routes.

When deploying outside Shopify, you may need to adapt the routing structure slightly depending on the platform.

Best Practices

  • Organize your functions in /src/routes/api/ by feature or endpoint purpose.
  • Never expose secrets on the client; keep all sensitive API keys server-side.
  • Log and monitor usage, especially for functions that might be rate-limited by third-party services.
  • Use TypeScript in your Hydrogen project to enforce type safety in requests and responses.
  • Cache where appropriate to reduce load on third-party APIs.

Summary

Serverless functions in Hydrogen are a key enabler of flexible, scalable, and secure custom storefronts. Whether you’re integrating with third-party APIs, protecting your backend logic, or customizing your Shopify experience, serverless functions provide a modern way to build robust backend capabilities without the need for infrastructure.

For developers building with Hydrogen and Oxygen, this feature is an indispensable part of the modern Shopify tech stack.

At Kolachi Tech, we specialize in custom Shopify Hydrogen development — from high-performance storefronts to API integrations and serverless architecture. If you’re building the future of eCommerce, we can help you accelerate it. Let’s talk about your project today.

Your Trusted Shopify Partner.

Get in touch with our expert Shopify consultants today and let’s discuss your ideas and business requirements.