### Install Dependencies and Run Example Source: https://github.com/prismicio/prismic-client/blob/master/examples/query-using-refs/README.md Follow these steps to install dependencies and run the Node.js example. ```sh # Clone the repository to your computer git clone https://github.com/prismicio/prismic-client.git cd prismic-client/examples/using-refs # Install the dependencies npm install # Run the example node index.js ``` -------------------------------- ### Install and Run Express Example Source: https://github.com/prismicio/prismic-client/blob/master/examples/with-express/README.md Follow these steps to clone the repository, install dependencies, and run the Express example. ```sh git clone https://github.com/prismicio/prismic-client.git cd prismic-client/examples/server-usage npm install node index.js ``` -------------------------------- ### Install and Run Custom Caching Example Source: https://github.com/prismicio/prismic-client/blob/master/examples/custom-query-caching/README.md Follow these commands to clone the repository, navigate to the example directory, install dependencies, and run the custom caching example. ```sh # 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 ``` -------------------------------- ### Install Dependencies and Run Server Example Source: https://github.com/prismicio/prismic-client/blob/master/examples/server-usage/README.md Instructions for setting up and running the server-side Prismic client example. This includes cloning the repository, navigating to the example directory, installing npm packages, and executing the script. ```sh git clone https://github.com/prismicio/prismic-client.git cd prismic-client/examples/server-usage npm install node index.js ``` -------------------------------- ### Run Multiple Languages Example Source: https://github.com/prismicio/prismic-client/blob/master/examples/query-multiple-languages/README.md Follow these commands to clone the repository, navigate to the example directory, install dependencies, and run the Node.js example. ```sh # 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 ``` -------------------------------- ### Install and Run Custom Timeout Example Source: https://github.com/prismicio/prismic-client/blob/master/examples/custom-query-timeout/README.md Follow these steps to clone the repository, install dependencies, and run the custom timeout example in Node.js. ```sh # Clone the repository to your computer git clone https://github.com/prismicio/prismic-client.git cd prismic-client/examples/custom-timeout # Install the dependencies npm install # Run the example node index.js ``` -------------------------------- ### Run Release Query Example Source: https://github.com/prismicio/prismic-client/blob/master/examples/query-using-releases/README.md Instructions for cloning the repository, installing dependencies, and running the Node.js example for querying content with releases. ```sh # 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 ``` -------------------------------- ### Run TypeScript Example Source: https://github.com/prismicio/prismic-client/blob/master/examples/with-typescript/README.md Instructions for setting up and running the TypeScript example. This includes cloning the repository, installing dependencies, and executing the script. ```bash # Clone the repository to your computer git clone https://github.com/prismicio/prismic-client.git cd prismic-client/examples/with-typescript # Install the dependencies npm install # Run the example npx tsx index.ts ``` -------------------------------- ### Install @prismicio/client Source: https://github.com/prismicio/prismic-client/blob/master/README.md Install the @prismicio/client library using npm. This command is essential before using the client in your project. ```bash npm install @prismicio/client ``` -------------------------------- ### Clone and Install Project Dependencies Source: https://github.com/prismicio/prismic-client/blob/master/CONTRIBUTING.md Clone the repository and install the necessary npm packages to begin development. ```sh git clone git@github.com:prismicio/prismic-client.git cd prismic-client npm install ``` -------------------------------- ### Install Canary Prerelease Source: https://github.com/prismicio/prismic-client/blob/master/CONTRIBUTING.md Install the canary prerelease version of the client for testing. This version is published on every push to master. ```sh npm install @prismicio/client@canary ``` -------------------------------- ### Install PR Prerelease Source: https://github.com/prismicio/prismic-client/blob/master/CONTRIBUTING.md Install a specific PR prerelease version of the client for testing. This version is published on every push to a PR and is deprecated when the PR is closed. ```sh npm install @prismicio/client@pr- ``` -------------------------------- ### Start Development Watcher Source: https://github.com/prismicio/prismic-client/blob/master/CONTRIBUTING.md Run the development watcher to automatically rebuild the project as you make changes. ```sh npm run dev ``` -------------------------------- ### Run Migration Script with tsx Source: https://github.com/prismicio/prismic-client/blob/master/examples/migrate/README.md This command installs dependencies and runs the TypeScript migration script using tsx. Ensure you have cloned the repository and navigated to the example directory. ```sh git clone https://github.com/prismicio/prismic-client.git cd prismic-client/examples/migrate npm install npx tsx migrate.ts ``` -------------------------------- ### Create and Query Prismic Client Source: https://github.com/prismicio/prismic-client/blob/master/README.md Use this snippet to create a Prismic client instance and query for content of a specific type. Ensure you have the @prismicio/client library installed. ```typescript import * as prismic from "@prismicio/client" // Create a client const client = prismic.createClient("my-repository") // Then query for your content const blogPosts = await client.getAllByType("blog_post") ``` -------------------------------- ### Create Write Client and Migration Plan for Content Migration Source: https://context7.com/prismicio/prismic-client/llms.txt Use `createWriteClient` to get a client for uploading assets and migrating documents. `createMigration` builds a plan for executing document and asset operations in a single `migrate()` call. Register assets and documents with the migration plan before executing. ```typescript import * as prismic from "@prismicio/client" // 1. Create the write client (requires a write token) const writeClient = prismic.createWriteClient("my-repo", { writeToken: process.env.PRISMIC_WRITE_TOKEN!, // Optional: override Migration and Asset API endpoints // migrationAPIEndpoint: "https://migration.prismic.io/", // assetAPIEndpoint: "https://asset-api.prismic.io/", }) // 2. Create a migration plan const migration = prismic.createMigration() // 3. Register assets (images, files) — resolved during migrate() const heroImage = migration.createAsset( "https://example.com/hero.jpg", "hero.jpg", { alt: "Hero image", notes: "Migrated from legacy CMS" }, ) // 4. Register documents — can reference assets and each other const homePage = migration.createDocument( { type: "page", lang: "en-us", uid: "home", tags: ["migrated"], data: { title: [{ type: "heading1", text: "Home", spans: [] }], hero_image: heroImage, // reference resolved at migration time }, }, "Home", // document title used in the Page Builder ) // Cross-document reference migration.createDocument( { type: "blog_post", lang: "en-us", uid: "first-post", data: { title: [{ type: "heading1", text: "First Post", spans: [] }], related_page: homePage, // resolved to a content relationship field }, }, "First Post", ) // 5. Execute the migration — uploads assets then creates/updates documents await writeClient.migrate(migration, { reporter: (event) => { switch (event.type) { case "start": console.log(`Migrating ${event.data.pending.documents} documents and ${event.data.pending.assets} assets`) break case "assets:creating": console.log(`Uploading asset ${event.data.current}/${event.data.total}: ${event.data.asset.name}`) break case "documents:creating": console.log(`Creating document ${event.data.current}/${event.data.total}`) break case "end": console.log(`Done. Migrated ${event.data.migrated.documents} documents, ${event.data.migrated.assets} assets.`) break } }, }) ``` -------------------------------- ### client.graphQLFetch Source: https://context7.com/prismicio/prismic-client/llms.txt A preconfigured `fetch` function for Prismic's GraphQL endpoint. Automatically injects the current ref and authorization headers. Designed to be passed directly to GraphQL clients like Apollo Client. Must use GET requests. ```APIDOC ## `client.graphQLFetch` — GraphQL API integration ### Description A preconfigured `fetch` function for Prismic's GraphQL endpoint. Automatically injects the current ref and authorization headers. Designed to be passed directly to GraphQL clients like Apollo Client. Must use GET requests. ### Usage ```typescript import * as prismic from "@prismicio/client" import { ApolloClient, HttpLink, InMemoryCache, gql } from "@apollo/client" const client = prismic.createClient("my-repo", { accessToken: process.env.PRISMIC_ACCESS_TOKEN, }) const apolloClient = new ApolloClient({ link: new HttpLink({ uri: prismic.getGraphQLEndpoint("my-repo"), fetch: client.graphQLFetch, // injects prismic-ref header automatically useGETForQueries: true, // required by Prismic }), cache: new InMemoryCache(), }) const { data } = await apolloClient.query({ query: gql` query { allBlog_posts { edges { node { title _meta { uid } } } } } `, }) ``` ``` -------------------------------- ### Integrate Prismic GraphQL API with Apollo Client Source: https://context7.com/prismicio/prismic-client/llms.txt Uses a preconfigured fetch function for Prismic's GraphQL endpoint, automatically injecting the current ref and authorization headers. Designed to be passed directly to GraphQL clients like Apollo Client. Must use GET requests. ```typescript import * as prismic from "@prismicio/client" import { ApolloClient, HttpLink, InMemoryCache, gql } from "@apollo/client" const client = prismic.createClient("my-repo", { accessToken: process.env.PRISMIC_ACCESS_TOKEN, }) const apolloClient = new ApolloClient({ link: new HttpLink({ uri: prismic.getGraphQLEndpoint("my-repo"), fetch: client.graphQLFetch, // injects prismic-ref header automatically useGETForQueries: true, // required by Prismic }), cache: new InMemoryCache(), }) const { data } = await apolloClient.query({ query: gql` query { allBlog_posts { edges { node { title _meta { uid } } } } } `, }) ``` -------------------------------- ### Content Migration with createWriteClient and createMigration Source: https://context7.com/prismicio/prismic-client/llms.txt Demonstrates how to create a write-capable client and a migration plan to upload assets and migrate documents to a Prismic repository. ```APIDOC ## `createWriteClient` and `createMigration` — Content migration `createWriteClient` creates a write-capable client that can upload assets and migrate documents to a Prismic repository via the Migration API. `createMigration` creates a migration plan that collects document and asset creation operations before executing them in a single `migrate()` call. ```typescript import * as prismic from "@prismicio/client" // 1. Create the write client (requires a write token) const writeClient = pr.createWriteClient("my-repo", { writeToken: process.env.PRISMIC_WRITE_TOKEN!, // Optional: override Migration and Asset API endpoints // migrationAPIEndpoint: "https://migration.prismic.io/", // assetAPIEndpoint: "https://asset-api.prismic.io/", }) // 2. Create a migration plan const migration = prismic.createMigration() // 3. Register assets (images, files) — resolved during migrate() const heroImage = migration.createAsset( "https://example.com/hero.jpg", "hero.jpg", { alt: "Hero image", notes: "Migrated from legacy CMS" }, ) // 4. Register documents — can reference assets and each other const homePage = migration.createDocument( { type: "page", lang: "en-us", uid: "home", tags: ["migrated"], data: { title: [{ type: "heading1", text: "Home", spans: [] }], hero_image: heroImage, // reference resolved at migration time }, }, "Home", // document title used in the Page Builder ) // Cross-document reference migration.createDocument( { type: "blog_post", lang: "en-us", uid: "first-post", data: { title: [{ type: "heading1", text: "First Post", spans: [] }], related_page: homePage, // resolved to a content relationship field }, }, "First Post", ) // 5. Execute the migration — uploads assets then creates/updates documents await writeClient.migrate(migration, { reporter: (event) => { switch (event.type) { case "start": console.log(`Migrating ${event.data.pending.documents} documents and ${event.data.pending.assets} assets`) break case "assets:creating": console.log(`Uploading asset ${event.data.current}/${event.data.total}: ${event.data.asset.name}`) break case "documents:creating": console.log(`Creating document ${event.data.current}/${event.data.total}`) break case "end": console.log(`Done. Migrated ${event.data.migrated.documents} documents, ${event.data.migrated.assets} assets.`) break } }, }) ``` ``` -------------------------------- ### Build Project for Production Source: https://github.com/prismicio/prismic-client/blob/master/CONTRIBUTING.md Build the project for production to see the production version. ```sh npm run build ``` -------------------------------- ### `asImageSrc` — Get image URL with imgix transforms Source: https://context7.com/prismicio/prismic-client/llms.txt Returns the URL of an image field with optional imgix image transformation parameters applied. Returns `null` for empty image fields. ```APIDOC ## `asImageSrc` — Get image URL with imgix transforms Returns the URL of an image field with optional imgix image transformation parameters applied. Returns `null` for empty image fields. ### Usage ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") const post = await client.getByUID("blog_post", "my-post") // Plain URL const src = prismic.asImageSrc(post.data.cover_image) // => "https://images.prismic.io/my-repo/cover.jpg" // With imgix transformations const transformed = prismic.asImageSrc(post.data.cover_image, { w: 800, h: 600, fit: "crop", sat: -50, // desaturate by 50% auto: "format", // auto WebP/AVIF q: 80, }) // => "https://images.prismic.io/my-repo/cover.jpg?w=800&h=600&fit=crop&sat=-50&auto=format&q=80" // Responsive view (thumbnail) const thumb = prismic.asImageSrc(post.data.cover_image.thumb, { w: 400 }) // Empty field → null const empty = prismic.asImageSrc(null) // => null ``` ``` -------------------------------- ### createClient Source: https://context7.com/prismicio/prismic-client/llms.txt Creates a Client instance for querying content from a Prismic repository. Accepts repository name or endpoint, and optional configuration. ```APIDOC ## createClient — Create a read client Creates a `Client` instance for querying content from a Prismic repository. Accepts either a repository name or a full CDN API endpoint, along with optional configuration for access tokens, route resolvers, default query parameters, and a custom `fetch` implementation. ```typescript import * as prismic from "@prismicio/client" // TypeScript: declare all document types for full inference type BlogPostDocument = prismic.PrismicDocumentWithUID< { title: prismic.TitleField; body: prismic.RichTextField }, "blog_post" > type SettingsDocument = prismic.PrismicDocumentWithoutUID< { site_name: prismic.KeyTextField }, "settings" > type AllDocumentTypes = BlogPostDocument | SettingsDocument const client = prismic.createClient("my-repo", { // Optional: secure access token for private repositories accessToken: process.env.PRISMIC_ACCESS_TOKEN, // Route resolver: populates document.url automatically routes: [ { type: "blog_post", path: "/blog/:uid" }, { type: "settings", path: "/" }, ], // Fallback URL for broken/archived document links brokenRoute: "/404", // Default params applied to every query defaultParams: { lang: "en-us" }, }) ``` ``` -------------------------------- ### Get Image URLs with `asImageSrc` and Imgix Transforms Source: https://context7.com/prismicio/prismic-client/llms.txt Retrieves the URL for an image field, optionally applying Imgix transformations for resizing, cropping, and format conversion. Returns null for empty image fields. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") const post = await client.getByUID("blog_post", "my-post") // Plain URL const src = prismic.asImageSrc(post.data.cover_image) // => "https://images.prismic.io/my-repo/cover.jpg" // With imgix transformations const transformed = prismic.asImageSrc(post.data.cover_image, { w: 800, h: 600, fit: "crop", sat: -50, // desaturate by 50% auto: "format", // auto WebP/AVIF q: 80, }) // => "https://images.prismic.io/my-repo/cover.jpg?w=800&h=600&fit=crop&sat=-50&auto=format&q=80" // Responsive view (thumbnail) const thumb = prismic.asImageSrc(post.data.cover_image.thumb, { w: 400 }) // Empty field → null const empty = prismic.asImageSrc(null) // => null ``` -------------------------------- ### Create a Prismic Client Instance Source: https://context7.com/prismicio/prismic-client/llms.txt Use `createClient` to instantiate a read-only client for fetching content. Configure repository access, route resolvers, and default query parameters. TypeScript users should declare all document types for full inference. ```typescript import * as prismic from "@prismicio/client" // TypeScript: declare all document types for full inference type BlogPostDocument = prismic.PrismicDocumentWithUID< { title: prismic.TitleField; body: prismic.RichTextField }, "blog_post" > type SettingsDocument = prismic.PrismicDocumentWithoutUID< { site_name: prismic.KeyTextField }, "settings" > type AllDocumentTypes = BlogPostDocument | SettingsDocument const client = prismic.createClient("my-repo", { // Optional: secure access token for private repositories accessToken: process.env.PRISMIC_ACCESS_TOKEN, // Route resolver: populates document.url automatically routes: [ { type: "blog_post", path: "/blog/:uid" }, { type: "settings", path: "/" }, ], // Fallback URL for broken/archived document links brokenRoute: "/404", // Default params applied to every query defaultParams: { lang: "en-us" }, }) ``` -------------------------------- ### Run All Tests Source: https://github.com/prismicio/prismic-client/blob/master/CONTRIBUTING.md Run all tests to ensure your changes do not break existing functionality. No failing tests are allowed. ```sh npm run test ``` -------------------------------- ### Create Client with CDN Repository Endpoint Source: https://github.com/prismicio/prismic-client/blob/master/messages/endpoint-must-use-cdn.md Use this method when creating a client with a repository endpoint. The endpoint's subdomain must feature the `.cdn` suffix. ```typescript import * as prismic from "@prismicio/client" // ✅ Correct const client = prismic.createClient("https://example-prismic-repo.cdn.prismic.io/api/v2") ``` ```typescript // ❌ Incorrect const client = prismic.createClient("https://example-prismic-repo.prismic.io/api/v2") ``` -------------------------------- ### Create Prismic Write Client Source: https://github.com/prismicio/prismic-client/blob/master/messages/avoid-write-client-in-browser.md Use this when creating a write client for your Prismic repository. Ensure the repository write token is provided. This client should not be exposed to the browser. ```typescript import * as prismic from "@prismicio/client" const writeClient = prismic.createWriteClient("example-prismic-repo", { writeToken: "xxx", }) ``` -------------------------------- ### Fetch Repository Metadata with client.getRepository Source: https://context7.com/prismicio/prismic-client/llms.txt Fetches metadata about the Prismic repository. The result is cached in memory for 5 seconds. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") const repository = await client.getRepository() console.log(repository.refs) // all refs (master + releases) console.log(repository.languages) // available languages console.log(repository.tags) // all tags in the repository ``` -------------------------------- ### Create Pull Request using GitHub CLI Source: https://github.com/prismicio/prismic-client/blob/master/CONTRIBUTING.md Open a pull request using the GitHub CLI. This is the first step in submitting your changes for review. ```sh gh pr create ``` -------------------------------- ### client.getRepository Source: https://context7.com/prismicio/prismic-client/llms.txt Fetches metadata about the Prismic repository, including refs, languages, forms, and integration field refs. The result is cached in memory for 5 seconds. ```APIDOC ## `client.getRepository` — Fetch repository metadata ### Description Fetches metadata about the Prismic repository, including refs, languages, forms, and integration field refs. The result is cached in memory for 5 seconds. ### Usage ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") const repository = await client.getRepository() console.log(repository.refs) // all refs (master + releases) console.log(repository.languages) // available languages console.log(repository.tags) // all tags in the repository ``` ``` -------------------------------- ### client.get Source: https://context7.com/prismicio/prismic-client/llms.txt Fetches a paginated list of documents matching arbitrary query parameters and filters. Returns a Query response object. ```APIDOC ## client.get — Generic paginated query Fetches a paginated list of documents matching arbitrary query parameters and filters. Returns a `Query` response object containing `results`, `total_results_size`, `page`, `next_page`, etc. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") // Paginated query with filters, ordering, and field projection const response = await client.get({ filters: [ prismic.filter.at("document.type", "blog_post"), prismic.filter.dateAfter("my.blog_post.published_at", new Date("2024-01-01")), ], orderings: [{ field: "my.blog_post.published_at", direction: "desc" }], fetch: ["blog_post.title", "blog_post.published_at"], pageSize: 20, page: 1, lang: "*", // all languages }) console.log(response.results) // document array console.log(response.total_results_size) // total matches console.log(response.next_page) // URL of next page or null // Abort long-running requests const controller = new AbortController() const responseWithAbort = await client.get({ filters: [prismic.filter.at("document.type", "article")], fetchOptions: { signal: controller.signal }, }) ``` ``` -------------------------------- ### Create Client with Proxied Endpoint (Not Recommended) Source: https://github.com/prismicio/prismic-client/blob/master/messages/prefer-repository-name.md When proxying a Prismic API v2 repository endpoint, use the `documentAPIEndpoint` option. Providing the proxied endpoint as the first argument is incorrect and can lead to issues. ```typescript import * as prismic from "@prismicio/client" // ✅ Correct const client = prismic.createClient("my-repo-name", { documentAPIEndpoint: "https://example.com/my-prismic-proxy", }) // ❌ Incorrect: repository name can't be inferred from a proxied endpoint const client = prismic.createClient("https://example.com/my-prismic-proxy", { documentAPIEndpoint: "https://example.com/my-prismic-proxy", }) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/prismicio/prismic-client/blob/master/CONTRIBUTING.md Run only the unit tests. Optionally, run in watch mode to automatically re-run tests when files change. ```sh npm run unit npm run unit:watch ``` -------------------------------- ### client.getRefs, client.getMasterRef, client.getReleases Source: https://context7.com/prismicio/prismic-client/llms.txt Fetches content refs for controlling which version of content to query. The master ref points to published content; release refs point to scheduled or draft releases. ```APIDOC ## `client.getRefs` / `client.getMasterRef` / `client.getReleases` — Manage content refs ### Description Fetches content refs for controlling which version of content to query. The master ref points to published content; release refs point to scheduled or draft releases. ### Usage ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") // Get all refs const refs = await client.getRefs() // Get only the master ref const masterRef = await client.getMasterRef() console.log(masterRef.ref) // ref string used for API queries // List all releases const releases = await client.getReleases() // Get a specific release by ID or label const release = await client.getReleaseByLabel("Upcoming Launch") console.log(release.ref) ``` ``` -------------------------------- ### Perform a Paginated Query with Filters Source: https://context7.com/prismicio/prismic-client/llms.txt Use `client.get` for paginated queries with filters, ordering, and field projection. The response includes document results, total count, and pagination information. Abort long-running requests using `AbortController`. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") // Paginated query with filters, ordering, and field projection const response = await client.get({ filters: [ prismic.filter.at("document.type", "blog_post"), prismic.filter.dateAfter("my.blog_post.published_at", new Date("2024-01-01")), ], orderings: [{ field: "my.blog_post.published_at", direction: "desc" }], fetch: ["blog_post.title", "blog_post.published_at"], pageSize: 20, page: 1, lang: "*", // all languages }) console.log(response.results) // document array console.log(response.total_results_size) // total matches console.log(response.next_page) // URL of next page or null // Abort long-running requests const controller = new AbortController() const responseWithAbort = await client.get({ filters: [prismic.filter.at("document.type", "article")], fetchOptions: { signal: controller.signal }, }) ``` -------------------------------- ### client.queryContentFromReleaseByID, queryContentFromReleaseByLabel, queryLatestContent Source: https://context7.com/prismicio/prismic-client/llms.txt Configures the client to query content from a specific Prismic release (draft/staged content) instead of the default published content. Call `queryLatestContent()` to reset to published content. ```APIDOC ## `client.queryContentFromReleaseByID` / `queryContentFromReleaseByLabel` / `queryLatestContent` — Control content version ### Description Configures the client to query content from a specific Prismic release (draft/staged content) instead of the default published content. Call `queryLatestContent()` to reset to published content. ### Usage ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") // Query from a specific release by its ID client.queryContentFromReleaseByID("YhE3YhEAACIA4321") const draftPost = await client.getByUID("blog_post", "upcoming-post") // Query from a release by its display label client.queryContentFromReleaseByLabel("Q1 Launch") const launchContent = await client.getAllByType("landing_page") // Reset to latest published content client.queryLatestContent() const publishedContent = await client.getAllByType("blog_post") ``` ``` -------------------------------- ### Fetch the First Matching Document Source: https://context7.com/prismicio/prismic-client/llms.txt Use `client.getFirst` to retrieve the first document matching specified parameters. This method automatically sets `pageSize: 1`. It throws a `NotFoundError` if no documents are found. Ensure proper error handling for cases where no document matches. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") try { const featuredPost = await client.getFirst({ filters: [ prismic.filter.at("document.type", "blog_post"), prismic.filter.at("my.blog_post.featured", true), ], }) console.log(featuredPost.data.title) // typed field access } catch (error) { if (error instanceof prismic.NotFoundError) { console.warn("No featured post found") } } ``` -------------------------------- ### client.enableAutoPreviews, enableAutoPreviewsFromReq, resolvePreviewURL Source: https://context7.com/prismicio/prismic-client/llms.txt Integrates Prismic's preview mechanism, which allows editors to preview unpublished content. In browser environments, auto-previews read the preview cookie automatically. In server environments (e.g. Next.js, Express), pass the incoming HTTP request object. ```APIDOC ## `client.enableAutoPreviews` / `enableAutoPreviewsFromReq` / `resolvePreviewURL` — Preview sessions ### Description Integrates Prismic's preview mechanism, which allows editors to preview unpublished content. In browser environments, auto-previews read the preview cookie automatically. In server environments (e.g. Next.js, Express), pass the incoming HTTP request object. ### Usage ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") // --- Browser usage: reads io.prismic.preview cookie automatically --- client.enableAutoPreviews() // --- Server usage (Next.js App Router Route Handler) --- // pages/api/preview.ts (Next.js Pages Router example) export default async function handler(req, res) { client.enableAutoPreviewsFromReq(req) const linkResolver = (doc) => { if (doc.type === "blog_post") return `/blog/${doc.uid}` return "/" } const redirectUrl = await client.resolvePreviewURL({ linkResolver, defaultURL: "/", // Automatically reads documentId and token from req.query }) res.redirect(redirectUrl) } // --- Disable previews (e.g. for static generation) --- client.disableAutoPreviews() ``` ``` -------------------------------- ### Manage Content Refs with client.getRefs Source: https://context7.com/prismicio/prismic-client/llms.txt Fetches content refs for controlling which version of content to query. The master ref points to published content; release refs point to scheduled or draft releases. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") // Get all refs const refs = await client.getRefs() // Get only the master ref const masterRef = await client.getMasterRef() console.log(masterRef.ref) // ref string used for API queries // List all releases const releases = await client.getReleases() // Get a specific release by ID or label const release = await client.getReleaseByLabel("Upcoming Launch") console.log(release.ref) ``` -------------------------------- ### Utility functions for Repository and Endpoint Management Source: https://context7.com/prismicio/prismic-client/llms.txt A set of low-level helper functions for working with Prismic repository identifiers and building raw Content API query URLs. ```APIDOC ## Utility functions — `getRepositoryEndpoint`, `getRepositoryName`, `getGraphQLEndpoint`, `isRepositoryName`, `isRepositoryEndpoint`, `buildQueryURL` A set of low-level helpers for working with Prismic repository identifiers and building raw Content API query URLs. ```typescript import * as prismic from "@prismicio/client" // Convert a repository name to its CDN API endpoint const endpoint = prismic.getRepositoryEndpoint("my-repo") // => "https://my-repo.cdn.prismic.io/api/v2" // Extract the repository name from an API endpoint URL const name = prismic.getRepositoryName("https://my-repo.cdn.prismic.io/api/v2") // => "my-repo" // Get the GraphQL API endpoint for a repository const graphqlEndpoint = prismic.getGraphQLEndpoint("my-repo") // => "https://my-repo.cdn.prismic.io/graphql" // Validate a string as a repository name prismic.isRepositoryName("my-repo") // => true prismic.isRepositoryName("not a name!") // => false // Validate a string as an API endpoint prismic.isRepositoryEndpoint("https://my-repo.cdn.prismic.io/api/v2") // => true // Build a Content API query URL manually (low-level) const client = prismic.createClient("my-repo") const queryURL = await client.buildQueryURL({ filters: [prismic.filter.at("document.type", "blog_post")], pageSize: 10, lang: "fr-fr", }) console.log(queryURL) // => "https://my-repo.cdn.prismic.io/api/v2/documents/search?ref=...&q=...&pageSize=10&lang=fr-fr" ``` ``` -------------------------------- ### Fetch a singleton document with `getSingle` Source: https://context7.com/prismicio/prismic-client/llms.txt Use `getSingle` to fetch the unique document for a "single type" custom type, such as settings or homepage. This method throws `NotFoundError` if the document is not found. ```typescript import * as prismic from "@prismicio/client" type SettingsDocument = prismic.PrismicDocumentWithoutUID< { site_name: prismic.KeyTextField; logo: prismic.ImageField }, "settings" > const client = prismic.createClient("my-repo") const settings = await client.getSingle("settings") console.log(settings.data.site_name) // KeyTextField ``` -------------------------------- ### Fetch documents by ID with `getByID`, `getByIDs`, `getAllByIDs` Source: https://context7.com/prismicio/prismic-client/llms.txt Fetch one or more documents using their Prismic document IDs. `getByID` retrieves a single document and throws `NotFoundError` if not found. `getByIDs` returns a paginated response, while `getAllByIDs` fetches all matching documents as a flat array. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") // Single document by ID const doc = await client.getByID("WW4bKScAAMAqmluX") // Multiple documents, paginated const page = await client.getByIDs(["WW4bKScAAMAqmluX", "U1kTRgEAAC8A5ldS"], { pageSize: 10, }) // All documents matching IDs (multi-page fetch) const docs = await client.getAllByIDs([ "WW4bKScAAMAqmluX", "U1kTRgEAAC8A5ldS", "YhE3YhEAACIA4321", ]) ``` -------------------------------- ### client.dangerouslyGetAll Source: https://context7.com/prismicio/prismic-client/llms.txt Fetches every document matching the given parameters, automatically paginating through all result pages with a 500ms delay between requests. Returns a flat array. Named "dangerously" as it can trigger many network requests for large datasets. ```APIDOC ## `client.dangerouslyGetAll` — Fetch all matching documents (multi-page) ### Description Fetches every document matching the given parameters, automatically paginating through all result pages with a 500ms delay between requests. Returns a flat array. Named "dangerously" as it can trigger many network requests for large datasets. ### Parameters - `options` (object) - Required - Configuration for the query, including filters, orderings, and limits. - `filters` (Array) - Optional - An array of filters to apply to the query. - `orderings` (Array) - Optional - An array of ordering configurations. - `limit` (number) - Optional - The maximum number of documents to fetch. ### Request Example ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") // Fetch all blog posts, capped at 50 documents const allPosts = await client.dangerouslyGetAll({ filters: [prismic.filter.at("document.type", "blog_post")], orderings: [{ field: "document.first_publication_date", direction: "desc" }], limit: 50, }) console.log(allPosts.length) // up to 50 allPosts.forEach((post) => console.log(post.uid, post.url)) ``` ### Response - `Array` - A flat array of all matching documents. ``` -------------------------------- ### client.getFirst Source: https://context7.com/prismicio/prismic-client/llms.txt Fetches the single first document matching the given parameters. Throws NotFoundError if no documents are returned. ```APIDOC ## client.getFirst — Fetch the first matching document Fetches the single first document matching the given parameters. Throws `NotFoundError` if no documents are returned. Automatically sets `pageSize: 1` unless `page` or `pageSize` are explicitly provided. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") try { const featuredPost = await client.getFirst({ filters: [ prismic.filter.at("document.type", "blog_post"), prismic.filter.at("my.blog_post.featured", true), ], }) console.log(featuredPost.data.title) // typed field access } catch (error) { if (error instanceof prismic.NotFoundError) { console.warn("No featured post found") } } ``` ``` -------------------------------- ### Fetch all matching documents with `dangerouslyGetAll` Source: https://context7.com/prismicio/prismic-client/llms.txt Use `dangerouslyGetAll` to fetch all documents matching given parameters. It automatically paginates and includes a delay between requests. Be cautious with large datasets as it can trigger many network requests. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") // Fetch all blog posts, capped at 50 documents const allPosts = await client.dangerouslyGetAll({ filters: [prismic.filter.at("document.type", "blog_post")], orderings: [{ field: "document.first_publication_date", direction: "desc" }], limit: 50, }) console.log(allPosts.length) // up to 50 allPosts.forEach((post) => console.log(post.uid, post.url)) ``` -------------------------------- ### Fetch documents with multiple filters Source: https://github.com/prismicio/prismic-client/blob/master/messages/filters-must-be-an-array.md Use an array for the `filters` parameter to apply multiple filtering conditions when fetching documents. Ensure the Prismic client is created before making the query. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo-name") const blogPosts = await client.getAllByType("blog_post", { filters: [ prismic.filter.not("my.document.uid", "hidden"), prismic.filter.dateBefore("document.first_publication_date", new Date("1991-03-07")), ], }) ``` -------------------------------- ### Create a New Feature Branch Source: https://github.com/prismicio/prismic-client/blob/master/CONTRIBUTING.md Create a new branch for your feature or fix using a descriptive naming convention. ```sh git checkout -b / ``` -------------------------------- ### Format Code Changes Source: https://github.com/prismicio/prismic-client/blob/master/CONTRIBUTING.md Format your code to ensure it meets project standards. Errors are not allowed. ```sh npm run format ``` -------------------------------- ### Create Prismic Non-Write Client Source: https://github.com/prismicio/prismic-client/blob/master/messages/avoid-write-client-in-browser.md Use this client for read-only operations in the browser. It does not require write credentials and is safe for browser environments. Be aware that the access token, if used, will be exposed. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("example-prismic-repo") ``` -------------------------------- ### Integrate Prismic Preview Sessions Source: https://context7.com/prismicio/prismic-client/llms.txt Integrates Prismic's preview mechanism, which allows editors to preview unpublished content. In browser environments, auto-previews read the preview cookie automatically. In server environments, pass the incoming HTTP request object. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") // --- Browser usage: reads io.prismic.preview cookie automatically --- client.enableAutoPreviews() // --- Server usage (Next.js App Router Route Handler) --- // pages/api/preview.ts (Next.js Pages Router example) export default async function handler(req, res) { client.enableAutoPreviewsFromReq(req) const linkResolver = (doc) => { if (doc.type === "blog_post") return `/blog/${doc.uid}` return "/" } const redirectUrl = await client.resolvePreviewURL({ linkResolver, defaultURL: "/", // Automatically reads documentId and token from req.query }) res.redirect(redirectUrl) } // --- Disable previews (e.g. for static generation) --- client.disableAutoPreviews() ``` -------------------------------- ### Control Content Version with client.queryContentFromReleaseByID Source: https://context7.com/prismicio/prismic-client/llms.txt Configures the client to query content from a specific Prismic release (draft/staged content) instead of the default published content. Call queryLatestContent() to reset to published content. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") // Query from a specific release by its ID client.queryContentFromReleaseByID("YhE3YhEAACIA4321") const draftPost = await client.getByUID("blog_post", "upcoming-post") // Query from a release by its display label client.queryContentFromReleaseByLabel("Q1 Launch") const launchContent = await client.getAllByType("landing_page") // Reset to latest published content client.queryLatestContent() const publishedContent = await client.getAllByType("blog_post") ``` -------------------------------- ### Generate Responsive Image `srcset` with `asImageWidthSrcSet` Source: https://context7.com/prismicio/prismic-client/llms.txt Generates a `srcset` attribute value for responsive images based on width. Supports default widths, custom widths with Imgix parameters, and Prismic's defined thumbnail sizes. Returns an object with `src` and `srcset` or null for empty fields. ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo") const post = await client.getByUID("blog_post", "my-post") // Default widths: 640, 828, 1200, 2048, 3840 const { src, srcset } = prismic.asImageWidthSrcSet(post.data.cover_image) // srcset => "https://...?width=640 640w, https://...?width=828 828w, ..." // Custom widths with imgix params const responsive = prismic.asImageWidthSrcSet(post.data.cover_image, { widths: [400, 800, 1200, 2400], auto: "format", fit: "crop", ar: "16:9", }) // Use Prismic responsive view thumbnails as srcset widths const thumbnails = prismic.asImageWidthSrcSet(post.data.cover_image, { widths: "thumbnails", // uses thumbnail dimensions defined in the type model }) // Usage in HTML const imgTag = `${post.data.cover_image.alt ?? ` ``` -------------------------------- ### Prismic Utility Functions for Repository and Query Handling Source: https://context7.com/prismicio/prismic-client/llms.txt These utility functions help in converting repository names to endpoints, extracting repository names from endpoints, and building raw Content API query URLs. Use `isRepositoryName` and `isRepositoryEndpoint` for validation. ```typescript import * as prismic from "@prismicio/client" // Convert a repository name to its CDN API endpoint const endpoint = prismic.getRepositoryEndpoint("my-repo") // => "https://my-repo.cdn.prismic.io/api/v2" // Extract the repository name from an API endpoint URL const name = prismic.getRepositoryName("https://my-repo.cdn.prismic.io/api/v2") // => "my-repo" // Get the GraphQL API endpoint for a repository const graphqlEndpoint = prismic.getGraphQLEndpoint("my-repo") // => "https://my-repo.cdn.prismic.io/graphql" // Validate a string as a repository name prismic.isRepositoryName("my-repo") // => true prismic.isRepositoryName("not a name!") // => false // Validate a string as an API endpoint prismic.isRepositoryEndpoint("https://my-repo.cdn.prismic.io/api/v2") // => true // Build a Content API query URL manually (low-level) const client = prismic.createClient("my-repo") const queryURL = await client.buildQueryURL({ filters: [prismic.filter.at("document.type", "blog_post")], pageSize: 10, lang: "fr-fr", }) console.log(queryURL) // => "https://my-repo.cdn.prismic.io/api/v2/documents/search?ref=...&q=...&pageSize=10&lang=fr-fr" ``` -------------------------------- ### `asLink` — Resolve any link field to a URL Source: https://context7.com/prismicio/prismic-client/llms.txt Converts any Prismic link field (web link, media link, or document link) or a `PrismicDocument` directly into a URL string. Returns `null` for empty or unresolvable fields. ```APIDOC ## `asLink` — Resolve any link field to a URL Converts any Prismic link field (web link, media link, or document link) or a `PrismicDocument` directly into a URL string. Returns `null` for empty or unresolvable fields. ### Usage ```typescript import * as prismic from "@prismicio/client" const client = prismic.createClient("my-repo", { routes: [{ type: "blog_post", path: "/blog/:uid" }] }) const post = await client.getByUID("blog_post", "my-post") const linkResolver = (doc: prismic.FilledContentRelationshipField) => { if (doc.type === "blog_post") return `/blog/${doc.uid}` return null } // Web link field → returns the URL directly const webUrl = prismic.asLink({ link_type: "Web", url: "https://example.com" }) // => "https://example.com" // Document link with route resolver (routes set on client) const docUrl = prismic.asLink(post.data.cta_link) // => "/blog/linked-post" // Document link with link resolver function const docUrlFn = prismic.asLink(post.data.cta_link, { linkResolver }) // => "/blog/linked-post" // Resolve a full PrismicDocument to its URL const postUrl = prismic.asLink(post, { linkResolver }) // => "/blog/my-post" // Empty field const empty = prismic.asLink({ link_type: "Any" }) // => null ``` ```