Prismic JavaScript + TypeScript Client

repository·master·Indexed 41 days ago

https://github.com/prismicio/prismic-client

The official JavaScript and TypeScript client library (@prismicio/client v7.22.1) for interacting with Prismic repositories. It enables developers to query content, apply filters, handle preview sessions, and manage content versions using Refs and Releases across both browser and server environments.

Tokens
18.8K
Snippets
76
Records
99
Agent score
51%

What's inside Prismic

  1. Run the custom caching example

    master

    To run the local demonstration of custom caching, follow these steps in your terminal:

    1. Clone the repository.
    2. Navigate to the specific example directory.
    3. Install dependencies.
    4. Execute the script using Node.js.
    # Clone the repository to your computer
    git clone https://github.com/prismicio/prismic-client.git
    cd prismic-client/examples/custom-caching
    
    # Install the dependencies
    npm install
    
    # Run the example
    node index.js
  2. Avoid using the write client in the browser

    master

    The @prismicio/client write client requires sensitive credentials, such as a writeToken or a Migration API key, to authenticate write queries. If you instantiate a write client in client-side code (the browser), these tokens will be exposed to the public, allowing malicious actors to gain write access to your Prismic repository.

    Best Practices:

    • Use the standard client for browser-side code: Use createClient for read-only operations. It is safe for the browser, though note that any access token provided will still be visible in the client-side network requests.
    • Use the write client only on the server: Reserve createWriteClient for server-side environments (e.g., Node.js, serverless functions) where your credentials can remain private.
    import * as prismic from "@prismicio/client"
    
    // ❌ DO NOT use this in the browser
    const writeClient = prismic.createWriteClient("example-prismic-repo", {
    	writeToken: "xxx",
    })
    
    // ✅ Use this for browser-side read operations
    const client = prismic.createClient("example-prismic-repo")
  3. Use @prismicio/client on the server

    master

    When using @prismicio/client in a server-side environment (like Node.js), the API usage is identical to the browser. However, because Node.js does not have a built-in fetch implementation in all versions/environments, you must explicitly provide a fetch function in your client configuration.

    In the provided example, node-fetch is used as a drop-in replacement for the browser's fetch() API.

    Caching Considerations:

    • Serverless architectures: If your server instances are started and stopped per-request, built-in caching is typically unnecessary.
    • Long-living servers: If you are running a persistent server, implementing custom caching is recommended to improve performance. See the custom-caching example for implementation details.
    // Conceptual usage pattern
    const client = createClient({ 
      // ... other config 
      fetch 
    });
  4. Run the multiple languages example

    master

    To run this specific example locally, follow these steps:

    1. Clone the repository.
    2. Navigate to the example directory.
    3. Install dependencies.
    4. Execute the script using Node.js.

    Note: This example uses node-fetch for Node.js environments. If you are porting this logic to a browser environment, you should remove the node-fetch import.

    # Clone the repository to your computer
    git clone https://github.com/prismicio/prismic-client.git
    cd prismic-client/examples/multiple-languages
    
    # Install the dependencies
    npm install
    
    # Run the example
    node index.js
  5. Implement custom request timeouts with AbortController

    master

    By default, fetch() implementations have varying timeout limits (e.g., 300s in Chrome, 90s in Firefox). To enforce a specific timeout duration when using @prismicio/client, use an AbortController. You can trigger the abort() method after a set duration to cancel the request.

    In Node.js environments older than version 15.0.0, you may need the abort-controller package. In modern Node.js or browser environments, AbortController is available globally and does not require an external library.

    Note: When moving from Node.js to the browser, you can remove node-fetch and abort-controller dependencies.

    import * as prismic from '@prismicio/client'
    import fetch from 'node-fetch'
    import { AbortController } from "abort-controller";
    
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 5000); // 5 second timeout
    
    try {
      const response = await prismic.get({ 
        // ... other options
        fetch, 
        signal: controller.signal 
      });
    } catch (e) {
      // Handle abort error
    }
  6. Use @prismicio/client with Express or other server libraries

    master

    To use @prismicio/client in a server-side environment like Express, Fastify, Koa, or Next.js, you should follow these patterns:

    1. Provide a fetch implementation: Since server environments may not have a native fetch API (depending on the Node.js version), provide a fetch() compatible function using a library like node-fetch.
    2. Implement Caching: You can improve performance by implementing client caching using libraries like quick-lru.
    3. Create a new client per request: A client can be stateful. To prevent data leakage (e.g., ensuring a preview request doesn't cause subsequent non-preview requests to return preview content), you must create a new client instance for every incoming request.
  7. Implement custom caching with @prismicio/client

    master

    Custom caching allows you to hook into a specific framework's cache or manage caching manually when using @prismicio/client on the server. While browsers use the global fetch() function and their own caching mechanisms by default, server-side environments (like Node.js) benefit from explicit caching implementations.

    To implement custom caching, you provide a custom fetch implementation to the client that manages the storage and retrieval of responses (for example, using a library like quick-lru).

    import * as prismic from '@prismicio/client'
    import QuickLRU from 'quick-lru'
    
    // Example pattern: Using a custom fetch with an LRU cache
    const cache = new QuickLRU({ max: 100 });
    
    const client = prismic.createClient({ repository: 'YOUR_REPO', fetch: async (url, options) => {
      if (cache.has(url)) {
        return cache.get(url);
      }
      const response = await fetch(url, options);
      const data = await response.clone();
      cache.set(url, data);
      return response;
    }});
  8. Run the Releases example

    master

    To run the local demonstration of the Releases query pattern, follow these steps in your terminal:

    1. Clone the repository.
    2. Navigate to the specific example directory.
    3. Install dependencies via npm.
    4. Execute the script using Node.js.
    # Clone the repository to your computer
    git clone https://github.com/prismicio/prismic-client.git
    cd prismic-client/examples/releases
    
    # Install the dependencies
    npm install
    
    # Run the example
    node index.js
  9. Query content using Refs

    master

    Refs are unique identifiers for different content versions in your Prismic repository. Every document edit or Release creation generates a new ref.

    You can control which content version is returned by the client in three ways:

    1. Global Client Configuration: Set a specific ref label when initializing the client to point all queries to that version.
    2. Default Behavior: By default, the client queries the latest published content.
    3. Per-Query Override: Pass a specific ref in the options object of an individual query method to override the client's global setting for that specific request.
    // 1. Global configuration (pointing to a specific ref label)
    const client = createClient({
      // ... other config
      ref: 'your-ref-label'
    });
    
    // 2. Per-query override
    const response = await client.getByUID('document-type', 'my-document', {
      ref: 'another-ref-label'
    });