0.0.2 • Published 1 year ago

@netlify/connect v0.0.2

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

connect-client

Use the Netlify Connect client to make GraphQL requests to your Data layer. This client automatically generates cache tags for any retrieved data from your Data Layer, enabling efficient caching of dynamic content on Netlify's CDN. When new data is published through your CMS, Netlify Connect sends a request to your site, containing the cache tags. These cache tags can be used to purge Netlify's CDN for any stale content.

The Netlify Connect client offers TypeScript type system support enhanced by gql.tada. This integration provides valuable editor feedback, auto-completion, and type hints.

Requirements

  • Site must be deployed to Netlify prior to starting
  • Install the GraphQL: Syntax Highlighting VSCode extension, for better GraphQL highlighting.

How to setup the Netlify connect client

  1. Install the client npm install @netlify/connect

  2. Generate required files for typescript support. The following command requires two environment variables to be passed:

NETLIFY_CONNECT_AUTH_TOKEN=<API token> NETLIFY_CONNECT_ENDPOINT=<API URL> npx netlify-connect-client connect-generate

This will create a netlify-connect directory which will have four files:

  • connect-schema.graphql: Your Data Layer's GraphQL schema.
  • graphql-env.d.ts: Typescript types generated by the GraphQL schema.
  • tsconfig.ts: Used to create the graphql-env.d.ts.
  • graphql.ts: Exports graphql function to access types within your project.
  1. Update typescript configuration.
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "@0no-co/graphqlsp",
        "schema": "netlify-connect/connect-schema.graphql"
      }
    ]
  }
}
  • The @0no-co/graphqlsp plugin is a TypeScript language server plugin to provide editor hints, diagnostics or errors when writing GraphQL documents
  1. VSCode settings Update the vscode settings to use the workspace version of typescript
{
  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.enablePromptUseWorkspaceTsdk": true
}

Setup Netlify function

Make sure you have the @netlify/functions installed in your project. Then add the following netlify function:

import { purgeCache } from "@netlify/functions";

export default async (req: Request) => {
  const body = await req.json();

  console.log(body);

  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();

  console.log(body);

  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 });
}

Setup Netlify Connect

Create a custom webhook for your Data Layer with the prefix invalidation_hook_. When a data update is performed, Netlify Connect will send a webhook to invalidate any pages that have been updated. Add your sites URL with a /connect-purge route. Example: https://invalidation_hook_my-awesome-site/connect-purge

How to use the connect-client

Make sure to add the following environment variables to your Netlify Site:

  • NETLIFY_CONNECT_AUTH_TOKEN: A GraphQL API token for your Data layer.
  • NETLIFY_CONNECT_ENDPOINT: Your Data Layer's GraphQL API URL.

From your project you can import graphql from netlify-connect/graphql and start writing GraphQL queries with type support.

To make a request to your api import query from netlify-connect-client

With Astro you need to pass in the Global Astro object to set the correct headers to purge the Netlify CDN cache when a data update is performed:

import { query } from "netlify-connect-client";
import { graphql } from "../../netlify-connect/graphql"; <-- 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;
};

With Next.js you can make the request without any additional options.

Options

The query function can be passed additional options:

  • endpointOverride the Data Layer API url.
  • token Override the Data Layer API token. This is used for making requests to your Data Layer with a permission scoped API token.
  • Astro 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 it works

Setting cache tags For dynamic content that is served from your site, the Connect client will create and add cache tags based on the GraphQL query. This will allow all subsequent requests for the content to be fetched from Netlify's CDN.

Purging cache tags When a data update is performed on your Data Layer, Netlify Connect will send a request to your site with cache tags that need to be invalidated. These cache tags can be passed to Netlify's purge cache api to purge any stale content on Netlify's CDN