@netlify/connect-client
TypeScript icon, indicating that this package has built-in type declarations

0.3.1 • Public • Published

connect-client

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.

Requirements

  • 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.

Set up Connect client

To set up the Connect client, complete the following steps:

  1. 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.

  2. Create a function to handle cache invalidation.

  3. Set up a custom webhook on your data layer.

Install the Connect client and configure your project

First, install the client and configure your project for querying and type system support:

  1. Install the client in your project:

    npm install @netlify/connect-client

  2. Create the following environment variables on Netlify:

    The client will use these values when you make queries from your project code.

  3. 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 and DATA_LAYER_API_URL environment variables either in a .env file or inline when you run the command.

    • If you have a .env file, run npx @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 @netlify/connect-client connect-generate

    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 the graphql function that you use to access types within your project

    Note that if your data layer schema changes at any point, you need to re-run this command to update the TypeScript types.

  4. Update the TypeScript configuration for your project to enable the @0no-co/graphqlsp plugin. In the ts-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.
  5. 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.

Create a function to handle cache invalidation

Use Netlify Functions to add a serverless function to your project that will check cache tags and purge the cache as needed.

  1. Install @netlify/functions in your project.

  2. Create a function file in your project’s function directory.

  3. 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 });
    }
  4. Commit this change to your Git repository and re-deploy your site.

Set up a custom webhook on your data layer

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.

Use Connect client to query your data layer

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.

Options

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.

How Connect client supports caching

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.

Limitations and billing

  • 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.

Troubleshooting

Connect client doesn’t reflect the latest schema

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 @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 @netlify/connect-client connect-generate

More resources

Readme

Keywords

Package Sidebar

Install

npm i @netlify/connect-client

Weekly Downloads

8

Version

0.3.1

License

ISC

Unpacked Size

42.5 kB

Total Files

54

Last publish

Collaborators

  • youvalv
  • berdav
  • vitaliyr
  • smnh
  • denar90
  • kathmbeck
  • rj-netlify
  • akardet
  • pieh
  • hrishikeshk
  • sarahetter
  • orinokai
  • ericap
  • seanroberts
  • skn0tt
  • mikewen
  • biilmann
  • marcus.netlify
  • jgantunes
  • eduardoboucas
  • netlify-bot
  • nasiba
  • ascorbic