Use the Connect client to make GraphQL API requests to your data layer in Netlify Connect and benefit from efficient caching of dynamic content on Netlify’s CDN. This is particularly helpful if your site uses a framework with SSR caching, such as Astro and Next.js.
To learn more about the caching optimizations, refer to the how Connect client supports caching section below.
The Connect client also offers TypeScript type system support, enhanced by gql.tada. By using the client, you get access to valuable editor feedback, auto-completion, and type hints based on your data layer’s GraphQL schema.
- A site deployed to Netlify.
- A data layer already configured in Netlify Connect.
- The GraphQL: Syntax Highlighting VSCode extension, for better GraphQL highlighting.
Refer to the limitations and billing section for additional information.
To set up the Connect client, complete the following steps:
-
Install the client and configure your project.
If you only want to use the client to query your data layer’s API and to get in-editor type system support, stop here. Otherwise, complete the following steps to set up the client and your data layer to support cache invalidation.
First, install the client and configure your project for querying and type system support:
-
Install the client in your project:
npm install @netlify/connect-client
-
Create the following environment variables on Netlify:
-
DATA_LAYER_API_TOKEN
: an API token for your data layer’s GraphQL API.- If you’re using API scopes to restrict access to certain data, we recommend that you use an unrestricted token for this step to ensure the generated TypeScript types reflect the complete schema for your data layer. In your data queries, you can override this with a scoped token by passing a
token
option to thequery
function.
- If you’re using API scopes to restrict access to certain data, we recommend that you use an unrestricted token for this step to ensure the generated TypeScript types reflect the complete schema for your data layer. In your data queries, you can override this with a scoped token by passing a
-
DATA_LAYER_API_URL
: your data layer’s GraphQL API URL
The client will use these values when you make queries from your project code.
-
-
Run the following command in your project to generate the required files for TypeScript support.
For this step, the client doesn’t have access to the environment variables you set on Netlify. So, you need to provide the
DATA_LAYER_API_TOKEN
andDATA_LAYER_API_URL
environment variables either in a .env file or inline when you run the command.-
If you have a
.env
file, runnpx -p @netlify/connect-client connect-init
-
If you don’t have a
.env
file, pass the variables inline:DATA_LAYER_API_TOKEN=<YOUR API TOKEN> DATA_LAYER_API_URL=<YOUR API URL> npx -p @netlify/connect-client connect-init
The command will create the following files:
│── .connect │ ├── schema.graphql │ └── types.d.ts ├── src │ ├── connect.d.ts │ └── netlify-connect │ └── graphql.ts
-
schema.graphql
: the GraphQL schema for your data layer -
types.d.ts
: the generated TypeScript types based on the GraphQL schema -
connect.d.ts
: a TypeScript declaration file -
graphql.ts
: a file that exports thegraphql
function that you use to access types within your project
Note that if your data layer schema changes at any point, follow our troubleshoot guide to update the TypeScript types.
-
-
Update the TypeScript configuration for your project to enable the
@0no-co/graphqlsp
plugin. In thets-config.json
for your project, add the following:{ "compilerOptions": { "plugins": [ { "name": "@0no-co/graphqlsp", "schema": "src/netlify-connect/connect-schema.graphql" } ] } }
- The
@0no-co/graphqlsp
plugin is a TypeScript language server plugin that provides editor hints, diagnostics, and errors when you write GraphQL documents.
- The
-
If you use VSCode, configure your VSCode settings to use the workspace version of TypeScript.
{ "typescript.tsdk": "node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true }
If you only want to use the client to query your data layer’s API and to get in-editor type system support, stop here. Otherwise, continue with the next two steps to set up the client and your data layer to support cache invalidation.
Use Netlify Functions to add a serverless function to your project that will check cache tags and purge the cache as needed.
-
Install
@netlify/functions
in your project. -
Create a function file in your project’s function directory.
-
Add the following function code to the file. Once deployed, the function will run on requests to
https://<YOUR DOMAIN>/connect-purge
.import { purgeCache } from "@netlify/functions"; export default async (req: Request) => { const body = await req.json(); if (!body?.cacheTags?.length) { return new Response("No tags to purge", { status: 400 }); } try { await purgeCache({ tags: body.cacheTags, }); } catch (error) { console.error(error); } return new Response("Purged!", { status: 202 }); }; export const config = { path: "/connect-purge", };
For Next.js, you will need to add a
connect-purge
API route:import { revalidateTag } from "next/cache"; import { NextRequest, NextResponse } from "next/server"; export async function POST(req: NextRequest) { const body = await req.json(); if (body.cacheTags?.length) { try { body.cacheTags.forEach((tag: string) => { return revalidateTag(tag); }); } catch (e) { console.error(e); } } return NextResponse.json({ success: true }, { status: 200 }); }
-
Commit this change to your Git repository and re-deploy your site.
Create a custom webhook for your data layer with the following:
-
Name: enter any name but it must include the prefix
invalidation_hook_
. -
URL: enter the URL for the function we created in the above step, in the format of
https://<YOUR DOMAIN>/connect-purge
When data changes in your data layer, Netlify automatically notifies all of your custom webhooks, including this one. Netlify will make a request to the connect-purge
path on your site and trigger the function.
Once you have completed the above three steps to configure the Connect client and your project, you can use the client to query your data layer’s GraphQL API.
Import the following in your code:
-
graphql
from../netlify-connect/graphql
to write GraphQL queries with type support. -
query
from@netlify/connect-client
to write requests to your data layer’s API. Learn more about the available options below.
Here is an example of a query in an Astro project:
import { query } from "@netlify/connect-client";
import { graphql } from "../netlify-connect/graphql"; // Note this is a relative path
const booksQuery = graphql(`
query books {
allContentfulBook {
nodes {
id: contentful_id
title
coverImage {
url
}
author {
name
}
}
}
}
`);
export const getBooks = async (Astro: any) => {
const res = await query(booksQuery, { Astro });
return res.allContentfulBook.nodes;
};
Note that Astro projects must pass the Global Astro object to query
to set the correct headers for purging the cache. This isn’t a requirement for Next.js projects.
You can pass the following additional options to the query
function:
-
endpoint
: to override the data layer’s API URL. -
token
: to override the data layer’s API token. Use this if you want to make requests with a scoped API token. -
Astro
: the Global Astro object. If you are using the Astro framework, you must pass the Global Astro Object to add the correct cache tags on the Response.
When a visitor makes a request to a page containing dynamic content from your data layer’s API, the Connect client automatically generates cache tags from the queries made to the API and adds the tags to the response. Netlify will respect the cache tags and cache the content on Netlify’s CDN before serving the response back to the visitor.
Later, when you update data in your CMS and that triggers a sync in your data layer, Netlify uses a custom webhook to send a request with the cache tags to your site. This request goes to the function you created to handle cache invalidation, which uses the cache tags to purge any stale content on Netlify’s CDN using Netlify’s purgeCache
helper. The next time a visitor makes a request for a page on your site, they will receive fresh content from the data layer and the response with the updated content will be cached on Netlify’s CDN.
- Cache optimization is only for Next.js and Astro. While you can use the client with any framework to query the API and get in-editor type system support, the built-in caching optimization is currently only supported for Astro and Next.js.
- Netlify Functions limits and billing apply. Since the client requires you to add a serverless function to your site, you should review the default deployment options and usage and billing documentation for Netlify Functions.
If the in-editor feedback, auto-completion, and type hints don’t reflect your data layer’s latest schema, you may need to regenerate the TypeScript files.
If you have a .env
file with the required environment variables, run:
npx -p @netlify/connect-client connect-generate
If you don’t have a .env
file, pass the variables inline:
DATA_LAYER_API_TOKEN=<YOUR API TOKEN> DATA_LAYER_API_URL=<YOUR API URL> npx -p @netlify/connect-client connect-generate
You can also pass the flag --env-file-path ../path/to/my/env/file
to load your env file from another location.
If you make a query to your data layer’s API and not all of the data you expect is returned, make sure your API token has the correct scopes for that data. Learn more in this troubleshooting tip for Netlify Connect.