---
title: "How to Add Product Manuals and Spec Sheets to Shopify Automatically (+ Free n8n Template)"
description: "Find each product's manuals and spec sheets on the manufacturer's site, check the model in code, approve doubtful ones in Slack, and show them on Shopify. Free n8n template."
canonical: "https://www.reganmcgregor.com.au/shopify-product-manuals/"
published: 2026-11-09
author: "Regan McGregor"
---

# How to Add Product Manuals and Spec Sheets to Shopify Automatically (+ Free n8n Template)

> Find each product's manuals and spec sheets on the manufacturer's site, check the model in code, approve doubtful ones in Slack, and show them on Shopify. Free n8n template.

*Last tested on n8n 2.46, November 2026.*

Shoppers want the user manual and the product spec sheet before they buy so they can check installation requirements, physical fit and what is in the box, and the manufacturer already publishes those files. Stores rarely link them because tracking down the right PDF for each exact model across regional sites and lookalike model codes takes longer than writing the product description. Attachment apps only display files you already have on your computer, while pasting a link into the description has to be done one product at a time and breaks whenever the manufacturer reorganises its website. This guide shows how to add a Documents table to a stock Shopify theme by hand, followed by a free n8n template that finds, checks, labels and publishes each product's manuals and spec sheets automatically.

<TemplateCallout
  repo="https://github.com/reganmcgregor/n8n-ecommerce-templates/tree/main/product-manuals-spec-sheets"
  title="Product manuals and spec sheets template for n8n"
>

- Finds each product's manuals, setup guides, datasheets and compliance documents on the manufacturer's own site.
- Checks the model number and the document type in code, and asks in Slack only when it isn't sure.
- Uploads PDFs to Shopify Files and fills a Documents table on the product page.

</TemplateCallout>

## What documents to show on a product page

When you sell another manufacturer's catalogue, a single support page can list ten downloads ranging from full manuals to regional compliance certificates and firmware zip files. Putting all of them on the product page overwhelms the shopper, whereas picking the four document types that answer pre-purchase and setup questions gives buyers confidence before checkout and cuts down on post-purchase "where is the manual?" support emails.

### User manuals

A user manual is the full reference guide for owning, configuring and troubleshooting the product after it is installed. Shoppers read it before buying to check whether a feature works the way they expect, such as whether a security camera supports local storage schedules or specific alert zones without a subscription. You can recognise a user manual by title words like `User Manual`, `User Guide`, `Instruction Manual`, `Owner's Manual` or `Operation Manual`, file names containing `user-guide`, `user_manual` or `-ug`, and opening lines that list a multi-chapter table of contents. In the store's Documents table, this type gets the **User manual** label.

### Setup and quick start guides

A setup guide or quick start guide covers physical mounting, wiring, what comes in the box and the first five minutes of configuration. Pre-purchase shoppers open it to check wall-mount hole spacing, cable clearances and power requirements before they order. These documents use titles like `Quick Start Guide`, `Quick Installation Guide`, `Installation Guide`, `Setup Guide` or `Getting Started`, and their URLs often contain `qsg`, `qig`, `quick-start` or `installation`. Many manufacturers publish setup guides as mobile-friendly HTML pages rather than PDFs, such as Ubiquiti's installation guide for the UniFi G5 PTZ at `dl.ui.com/qig/uvc-g5-ptz`. In the table, these are labelled **Setup guide**.

### Datasheets and spec sheets

A product datasheet and a product spec sheet are the same document under two names: a one-to-four-page engineering summary of dimensions, power draw, operating temperatures, lens angles, network standards and part numbers. Commercial buyers and installers rely on a product datasheet to verify compatibility and compare two models side by side without reading a 60-page manual. You can spot spec sheets by titles containing `Datasheet`, `Data Sheet`, `Technical Specifications` or `Specification Sheet`, and URLs ending in `datasheet.pdf`, `-ds.pdf` or `/techspecs/`. In the table, every spec sheet is labelled **Datasheet**.

### Compliance documents

Compliance documents include EU and UK declarations of conformity and regulatory certificates. Most shoppers do not read them, yet business and government buyers sometimes need them for procurement sign-off, and a declaration usually sits in the same download list as the manual, under the same model number. Recognising them by phrases like `Declaration of Conformity`, `EU Declaration`, `UK Declaration` or `Certificate of Conformity` (and file names ending in `-doc.pdf` or `/compliance/`) stops a one-page legal certificate from being mislabelled as the product's user manual. In the table, they are kept as labelled reference under **Compliance document**, and the template includes an `include_compliance` setting if you prefer to leave them off.

### What to leave out

Firmware archives, software utilities, range-wide marketing brochures and guides for optional accessories do not belong in a product's document table unless the product is that exact accessory. When a search for the UniFi G5 PTZ (`UVC-G5-PTZ`) turns up the installation guide for one of its mount accessories (`uacc-g5-ptz-icm`), attaching that mount guide to the camera page confuses buyers about what is included in the box. Likewise, when a manufacturer links both a generic "Tapo Camera Quick Installation Guide" for the whole range and a specific "Tapo C211 V3 Installation and User Guide", only the model-specific guide should go on the page.

Every document you show should come straight from the manufacturer's own domains, such as `tp-link.com`, `tapo.com`, `vigi.com` or `ui.com`, and never from another retailer, a forum or a third-party manual-hosting site. Sourcing directly from the manufacturer guarantees that the PDF is accurate and current, and anyone who inspects the source link can see it came from the official brand. While [Google can index PDF files](https://developers.google.com/search/docs/crawling-indexing/indexable-file-types), your product page is still the page you want ranking in search results, which is why linking the documents from a clean table on the product page works better for both shoppers and search engines than leaving buyers to hunt for raw PDFs on Google.

## How to add a PDF to a Shopify product page

If you only have a handful of products and already have their PDFs on hand, you can add a Documents table to a stock Shopify theme (such as Horizon) in the admin without editing any theme code files or installing an app. The Shopify community threads about adding a PDF download keep running into the same hurdle: a plain file metafield cannot be connected to a link block in the theme editor, and it cannot store a label or an external link for HTML setup guides. Using a metaobject and a short Custom Liquid block solves both problems, and you can stop at the end of Step 6 if you do not need automation.

## Step 1: Upload the document to Shopify Files

In your Shopify admin, go to **Content > Files** and click **Upload files** to add your PDF to Shopify Files. Hosting the PDF on your own store means the download link (`https://your-store.com/cdn/shop/files/tapo-c211-user-manual.pdf`) stays live even when the manufacturer redesigns its support site and breaks its old URLs. Keep the original manufacturer URL for interactive HTML setup guides or documents that change every few weeks, and note that [Shopify's file upload limit](https://help.shopify.com/en/manual/shopify-admin/productivity-tools/file-uploads) for generic files is 20 MB, so any PDF larger than 20 MB should be linked directly from the manufacturer's server.

## Step 2: Create a Product document metaobject

A single file metafield only holds a file reference, which means it cannot tell the shopper whether the file is a user manual or a datasheet, cannot link to an online HTML setup guide, and cannot record where the document came from. Using Shopify metaobjects lets you bundle the title, the document type, the hosted file, a fallback URL, the original source URL and the model number into one structured entry.

In the Shopify admin, open **Settings > Custom data > Metaobjects** and click **Add definition**. Name it `Product document`, check that the type key is `product_document`, keep **Storefronts access** turned on so the theme can read it, and add these six fields:

| Field | Key | Type |
|---|---|---|
| Title | `title` | Single line text (required) |
| Document type | `document_type` | Single line text (required), choices: User manual, Setup guide, Datasheet, Compliance document |
| File | `file` | File |
| Link | `url` | URL |
| Source | `source_url` | URL |
| Model | `model` | Single line text |

![A Product document entry for the Tapo C211 user manual, showing the six fields](./_attachments/shopify-product-manuals/product-document-entry.png "One Product document entry: the six fields from the definition, and the product that references it.")

## Step 3: Add a Documents field to products

Still in **Settings > Custom data**, open **Products** and click **Add definition**. Set the name to `Documents`, the namespace and key to `custom.documents`, and choose **Metaobject** as the type, selecting your **Product document** definition and choosing **List of entries** so a product can hold a manual, a setup guide and a datasheet at the same time. Turn on the pin icon so the field appears at the top of the product editor, then click **Save**.

## Step 4: Fill it on one product

Open a product in **Products**, scroll down to the **Metafields** section, click **Documents** and choose **Add entry** > **Create new entry**. Fill in the title (for example, `Tapo C211 user manual`), pick `User manual` under **Document type**, select the PDF you uploaded in Step 1 under **File** (or paste an external link under **Link** for an HTML guide), paste the manufacturer's original download URL into **Source**, and enter `Tapo C211` in **Model**. Save the entry, add any setup guide or datasheet entries the same way, and save the product.

![The Documents field on the Tapo C211 with three entries](./_attachments/shopify-product-manuals/admin-documents-field.png "A product's Documents field linked to three Product document entries.")

## Step 5: Show the Documents table

Shopify's stock Horizon theme has no built-in block that loops over a list of metaobjects, and the theme editor does not offer a file field as a dynamic link source on text or button blocks, which is why we use a **Custom Liquid** block. In the admin, go to **Online Store > Themes**, click the three dots on your current theme and choose **Duplicate** so you have a safe working copy, then click **Customize** on the copy.

At the top of the theme editor, switch to a product template and preview the product you edited in Step 4. In the left sidebar under **Product information**, click **Add block**, choose **Custom Liquid**, drag it directly beneath the **Description** block, and paste this snippet into the Liquid field:

```liquid
{%- assign documents = product.metafields.custom.documents.value -%}
{%- if documents != blank -%}
  <div class="product-documents">
    <h2 class="h5">Manuals and documents</h2>
    <table>
      <thead>
        <tr><th scope="col">Document</th><th scope="col">Type</th></tr>
      </thead>
      <tbody>
        {%- for doc in documents -%}
          {%- liquid
            assign doc_url = doc.url.value
            assign doc_format = ''
            if doc.file.value != blank
              assign doc_url = doc.file.value.url
              assign doc_format = doc.file.value.url | split: '?' | first | split: '.' | last | upcase
            endif
          -%}
          {%- if doc_url != blank -%}
            <tr>
              <td>
                <a href="{{ doc_url }}" target="_blank" rel="noopener">{{ doc.title.value | escape }}</a>
                {%- if doc_format != blank %} ({{ doc_format }}){% endif -%}
              </td>
              <td>{{ doc.document_type.value | escape }}</td>
            </tr>
          {%- endif -%}
        {%- endfor -%}
      </tbody>
    </table>
  </div>
  <style>
    .product-documents { margin-top: 1.5rem; }
    .product-documents table { width: 100%; border-collapse: collapse; }
    .product-documents th, .product-documents td { text-align: left; padding: 0.6rem 0.5rem 0.6rem 0; border-bottom: 1px solid rgb(var(--color-foreground-rgb, 0 0 0) / 0.12); }
    .product-documents th { font-weight: 600; }
  </style>
{%- endif -%}
```

When an entry has a hosted file in Shopify Files, the snippet uses `doc.file.value.url` and appends the file extension in brackets, such as `(PDF)`. When an entry is an online HTML guide with no uploaded file, it falls back to `doc.url.value` without a file-type suffix. If a product has no documents yet, `documents` is blank and nothing is rendered on the page.

![The Documents table Custom Liquid block in the Horizon theme editor, with the rendered table in the preview](./_attachments/shopify-product-manuals/theme-editor-custom-liquid-block.png "The Custom Liquid block (named Documents table) under the description, and the table it renders.")

## Step 6: Check it

Click **Save** in the theme editor, open the preview of your product page, and click each row in the **Manuals and documents** table. Check that uploaded PDFs open in a new tab from your store's `/cdn/shop/files/` address and that products without documents show no empty heading. If you only have a few products, you are done; if you want n8n to run Steps 1 and 4 for every product in your catalogue (and find the PDFs on the manufacturer's site first), continue to the next section.

## How to add product manuals to Shopify automatically with n8n

Adding documents by hand works well when you already have the files, and so do Shopify PDF attachment apps like [Easify Product Attachments](https://apps.shopify.com/ease-product-attachments) (free), [Agile Attachments](https://apps.shopify.com/agile-attachments) (free to US$9.99 a month), [Enchiridion](https://apps.shopify.com/enchiridion) (from US$1.99 a month), [PS Product Datasheets](https://apps.shopify.com/ps-product-datasheets) (from US$5 a month) and [Lambda File Downloads](https://apps.shopify.com/lambda-file-downloads) (US$19.99 a month, all checked November 2026). Those apps do a neat job of displaying files you upload yourself or generating spec sheets from existing metafields, whereas the hard work for a multi-brand retailer is finding the right manual and datasheet for each exact model and rejecting lookalike models. The n8n workflow below automates that discovery, verification and upload loop, and triggers on any product you tag with `documents`.

### What you'll build

On a security camera store running stock Horizon with TP-LINK and Ubiquiti products, tagging the **TP-Link Tapo C211** (`Tapo C211`) produces a three-row table on the product page: **Tapo C211 user manual (PDF)**, **Tapo C211 setup guide**, and **Tapo C211 datasheet (PDF)**, with the PDFs served from the store's own `/cdn/shop/files/tapo-c211-user-manual.pdf` address. When the workflow meets an ambiguous file, such as a family app guide or a datasheet for a lookalike model like the `VIGI C540-W` when checking the `VIGI C540`, it holds that file back and posts an interactive review card to Slack with **Approve**, **Reject** and **Change type** buttons.

![The Tapo C211 product page with the Manuals and documents table](./_attachments/shopify-product-manuals/tapo-c211-documents-table.png "The finished Manuals and documents table on the Tapo C211 product page in Horizon.")

![The n8n canvas with four lanes: Setup, Find, Review and Publish](./_attachments/shopify-product-manuals/n8n-template-canvas.png "The four-lane n8n workflow: Setup, Find, Review and Publish.")

### What you need

- n8n with Data Tables (self-hosted or Cloud, tested on n8n 2.46). A Supabase version of the same workflow is also in the GitHub repo if you prefer external Postgres tables.
- A custom app in your Shopify store using the client credentials grant with eight Admin API scopes: `read_products`, `write_products`, `read_files`, `write_files`, `read_metaobjects`, `write_metaobjects`, `read_metaobject_definitions` and `write_metaobject_definitions`.
- A Slack app with a bot token (`chat:write` scope), Interactivity turned on pointing to your n8n webhook URL, and its signing secret stored in an n8n Crypto credential. This is optional if you set `review_mode` to `none`.
- DataForSEO API credentials (optional) if you turn on `use_search` to supplement links found on the manufacturer's product page.
- Each product's vendor, its model number in the `custom.mpn` metafield (or the variant SKU), and, for the free path, its official product page URL in `custom.manufacturer_url`. No AI model or LLM API key is needed.

### How it works

The workflow is split into four lanes on one canvas so discovery, human review and Shopify file processing never block one another:

1. Setup (run once) creates the `documents` and `document_searches` Data Tables, creates the `Product document` metaobject definition (`product_document`), and adds three pinned product metafield definitions (`custom.documents`, `custom.mpn` and `custom.manufacturer_url`).
2. Find (runs hourly on products tagged `documents`) reads links from the product's manufacturer page and up to two of its model-specific support or download pages for free, optionally runs one cached Google search per product via DataForSEO, sends a `HEAD` request to every candidate link, reads text only from HTML guides, checks the exact model number and document type in code, and saves each row as `ready`, `review` or `rejected` with a clear reason.
3. Review (Slack) groups `review` rows into one Slack message per product so a person can click **Approve**, **Reject** or **Change type** on doubtful matches (such as family guides that do not name the model in the title, or files naming a longer model code like `VIGI C540-W`).
4. Publish (runs every 10 minutes, or immediately after a Slack approval) deduplicates files across regional URLs using their HTTP `ETag`, keeps one document per type in a consistent order, uploads PDFs to Shopify Files with clean filenames (`tapo-c211-user-manual.pdf`), waits until Shopify marks each file `READY`, and writes the metaobject entries and the product's `custom.documents` list.

## Step 7: Create the tables, the document type and the Documents field

If you skipped the steps above or want to add the `Model number (MPN)` and `Manufacturer page` fields in one click, the **Setup** lane creates both n8n Data Tables and all Shopify definitions idempotently. Start with a Manual Trigger connected to an Edit Fields (Set) node named **`Setup settings`** in JSON mode:

```json
{
  "store_domain": "your-store.myshopify.com",
  "namespace": "custom",
  "documents_key": "documents",
  "mpn_key": "mpn",
  "manufacturer_url_key": "manufacturer_url",
  "metaobject_type": "product_document"
}
```

Next, add two Data Table nodes in series, **`Create documents`** and **`Create document_searches`** (Data table > Create, with **Options > Create if not exists** turned on), so the workflow has somewhere to track every candidate URL, its HTTP fingerprint, its review state and its Shopify IDs. Configure the columns for `documents` as follows:

| Column | Type |
|---|---|
| `product_id` | string |
| `product_title` | string |
| `model` | string |
| `url` | string |
| `source_page` | string |
| `found_via` | string |
| `doc_title` | string |
| `doc_type` | string |
| `label` | string |
| `evidence` | string |
| `status` | string |
| `reason` | string |
| `fingerprint` | string |
| `file_url` | string |
| `mime` | string |
| `size_kb` | number |
| `file_id` | string |
| `metaobject_id` | string |
| `slack_channel` | string |
| `slack_ts` | string |
| `found_at` | date |
| `uploaded_at` | date |
| `published_at` | date |

Configure the columns for `document_searches` as follows:

| Column | Type |
|---|---|
| `query` | string |
| `product_id` | string |
| `results` | string |
| `cost` | number |
| `fetched_at` | date |

After the table nodes, add an HTTP Request node named **`Get Shopify token for Setup`** that exchanges your app's client credentials for a short-lived Admin API token (`POST https://<store_domain>/admin/oauth/access_token`, **Generic Credential Type > Custom Auth** holding `{"body": {"client_id": "...", "client_secret": "..."}}`, form body `grant_type=client_credentials`, with **Execute Once** and **Retry on Fail** turned on). Every Shopify GraphQL node in the workflow sends a `POST` request to `https://<store_domain>/admin/api/2026-10/graphql.json` with an `X-Shopify-Access-Token` header set to that token.

Connect **`Create the document type`** (HTTP Request) to create the `product_document` metaobject definition with public storefront access and the four allowed document type choices:

```graphql
mutation DocumentType($def: MetaobjectDefinitionCreateInput!) {
  metaobjectDefinitionCreate(definition: $def) {
    metaobjectDefinition { id type }
    userErrors { field message code }
  }
}
```

Set its GraphQL `variables` expression to:

```javascript
{ def: {
  type: $('Setup settings').first().json.metaobject_type, name: 'Product document', displayNameKey: 'title',
  access: { storefront: 'PUBLIC_READ' },
  fieldDefinitions: [
    { key: 'title', name: 'Title', type: 'single_line_text_field', required: true },
    { key: 'document_type', name: 'Document type', type: 'single_line_text_field', required: true,
      validations: [{ name: 'choices', value: JSON.stringify(['User manual', 'Setup guide', 'Datasheet', 'Compliance document']) }] },
    { key: 'file', name: 'File', type: 'file_reference' },
    { key: 'url', name: 'Link', type: 'url' },
    { key: 'source_url', name: 'Source', type: 'url' },
    { key: 'model', name: 'Model', type: 'single_line_text_field' }
  ] } }
```

Because `metaobjectDefinitionCreate` returns no ID when the definition already exists from Step 2, connect **`Look up the document type`** (HTTP Request) next so the workflow always has the metaobject definition ID before creating the product metafields:

```graphql
query DocumentType($type: String!) {
  metaobjectDefinitionByType(type: $type) { id type }
}
```

Use this `variables` expression:

```javascript
{ type: $('Setup settings').first().json.metaobject_type }
```

Connect **`Add the product fields`** (HTTP Request) to create and pin the `Documents` list field, the `Model number (MPN)` text field and the `Manufacturer page` URL field in a single GraphQL mutation:

```graphql
mutation ProductFields($docs: MetafieldDefinitionInput!, $mpn: MetafieldDefinitionInput!, $url: MetafieldDefinitionInput!) {
  documents: metafieldDefinitionCreate(definition: $docs) { createdDefinition { id } userErrors { field message code } }
  mpn: metafieldDefinitionCreate(definition: $mpn) { createdDefinition { id } userErrors { field message code } }
  manufacturer_url: metafieldDefinitionCreate(definition: $url) { createdDefinition { id } userErrors { field message code } }
}
```

Set its `variables` expression to:

```javascript
(() => {
  const s = $('Setup settings').first().json;
  const id = $json.data.metaobjectDefinitionByType.id;
  const def = (name, key, type, extra) => Object.assign({ name, namespace: s.namespace, key, type, ownerType: 'PRODUCT', pin: true }, extra || {});
  return {
    docs: def('Documents', s.documents_key, 'list.metaobject_reference', { validations: [{ name: 'metaobject_definition_id', value: id }] }),
    mpn: def('Model number (MPN)', s.mpn_key, 'single_line_text_field'),
    url: def('Manufacturer page', s.manufacturer_url_key, 'url', { description: "The manufacturer's page for this exact model" })
  };
})()
```

Finish the Setup lane with a Code node named **`Report setup`** so you get a plain summary whether you run Setup for the first time (`Product document type: created / Documents field: created`) or run it a second time (`already there` on every line):

```javascript
const say = (name, r) => !r ? name + ': no reply' : r.userErrors && r.userErrors.length
  ? name + ': ' + (r.userErrors.every(e => e.code === 'TAKEN') ? 'already there' : r.userErrors.map(e => e.message).join('; '))
  : name + ': created';
const t = $('Create the document type').first().json.data || {};
const f = $json.data || {};
return [{ json: { result: [
  say('Product document type', t.metaobjectDefinitionCreate),
  say('Documents field', f.documents), say('Model number field', f.mpn), say('Manufacturer page field', f.manufacturer_url)
].join('\n') } }];
```

## Step 8: Choose the products and the manufacturer's domains

The **Find** lane runs on a schedule (for example, hourly) or manually, picks up a batch of products tagged `documents`, and checks that each product has both a model number and at least one official domain listed for its vendor. Add an Edit Fields (Set) node named **`Find settings`** in JSON mode (`use_search` ships `false` so the template uses the free path until you turn search on):

```json
{
  "store_domain": "your-store.myshopify.com",
  "queue_tag": "documents",
  "product_ids": [],
  "batch_size": 5,
  "namespace": "custom",
  "mpn_key": "mpn",
  "manufacturer_url_key": "manufacturer_url",
  "use_sku_if_no_mpn": true,
  "manufacturer_domains": {
    "TP-LINK": [
      "tp-link.com",
      "vigi.com",
      "tapo.com"
    ],
    "Ubiquiti": [
      "ui.com"
    ]
  },
  "family_prefixes": [
    "Tapo",
    "VIGI",
    "UniFi",
    "UVC"
  ],
  "exclude_patterns": [],
  "follow_support_pages": true,
  "max_pages": 3,
  "max_candidates": 12,
  "use_search": false,
  "search_words": "user guide datasheet",
  "search_location": "Australia",
  "language_code": "en",
  "search_depth": 20,
  "cache_days": 30,
  "include_compliance": true,
  "review_mode": "uncertain",
  "user_agent": "Mozilla/5.0 (compatible; YourStoreBot/1.0; +https://your-store.com)"
}
```

In `manufacturer_domains`, map each Shopify `vendor` name (matched case-insensitively) to the domains that brand uses for its product pages and file downloads. For example, TP-LINK hosts Tapo and VIGI manuals across `tp-link.com`, `tapo.com` and `vigi.com`, while Ubiquiti serves pages from `techspecs.ui.com` and files from `dl.ui.com`, both of which match `ui.com`. Any link outside those domains is ignored, so a retailer's copy or a third-party manual site can never slip in.

After **`Find settings`**, connect **`Read cached searches`** (Data table > Get from `document_searches` where `fetched_at` is greater than or equal to `={{ $now.minus($('Find settings').first().json.cache_days, 'days').toISO() }}`, **Return All**, **Execute Once**, **Always Output Data**), followed by **`Read existing documents`** (Data table > Get all rows of `documents`, **Execute Once**, **Always Output Data**) and your Shopify token node. Then add **`Read queued products`** (HTTP Request) to fetch the next batch of tagged products along with their first SKU, `custom.mpn` and `custom.manufacturer_url`:

```graphql
query Queued($q: String!, $n: Int!, $ns: String!, $mpn: String!, $url: String!) {
  products(first: $n, query: $q) {
    nodes {
      id title vendor
      variants(first: 1) { nodes { sku } }
      mpn: metafield(namespace: $ns, key: $mpn) { value }
      page: metafield(namespace: $ns, key: $url) { value }
    }
  }
}
```

Set the `variables` expression on **`Read queued products`** to:

```javascript
(() => {
  const s = $('Find settings').first().json;
  const q = s.product_ids.length ? s.product_ids.map(id => 'id:' + id).join(' OR ') : 'tag:' + s.queue_tag;
  return { q, n: s.batch_size, ns: s.namespace, mpn: s.mpn_key, url: s.manufacturer_url_key };
})()
```

Connect a Code node named **`Build the product list`** to match each product's vendor to its allowed domains, fall back to the variant SKU if `custom.mpn` is empty and `use_sku_if_no_mpn` is `true`, check for a cached search hit, and flag products that cannot be searched:

```javascript
const s = $('Find settings').first().json;
const products = (($input.first().json.data || {}).products || { nodes: [] }).nodes;
const domainsFor = vendor => {
  const k = Object.keys(s.manufacturer_domains).find(v => v.toLowerCase() === String(vendor || '').toLowerCase());
  return k ? s.manufacturer_domains[k].map(d => d.toLowerCase().replace(/^www\./, '')) : [];
};
const cached = $('Read cached searches').all().map(i => i.json).filter(r => r.query);
return products.map(p => {
  const sku = ((p.variants.nodes[0] || {}).sku || '').trim();
  const model = ((p.mpn || {}).value || (s.use_sku_if_no_mpn ? sku : '')).trim();
  const domains = domainsFor(p.vendor);
  // One plain search per product. The manufacturer's domains are kept in code, not with site:,
  // because DataForSEO charges about five times as much for a site: search.
  const query = p.vendor + ' ' + model + ' ' + s.search_words;
  const hit = cached.find(r => r.query === query);
  return { json: {
    product_id: p.id.split('/').pop(), title: p.title, vendor: p.vendor, model, domains,
    manufacturer_url: (p.page || {}).value || '', query,
    cached_results: hit ? JSON.parse(hit.results || '[]') : null,
    skip: !model ? 'no model number' : !domains.length ? 'no manufacturer domains listed for ' + p.vendor : ''
  } };
});
```

Connect **`Has a model and domains?`** (If node with condition `={{ !$json.skip }}`) to split valid products from incomplete ones. When a product has no model number, such as a generic `Universal Camera Wall Bracket` with no MPN or SKU, the false branch sends it to **`Note skipped products`** (Code), which writes a `skipped` row (`reason: "no model number"`) to `documents` so you can see why nothing was attached:

```javascript
const now = new Date().toISOString();
return $input.all().map(i => ({ json: { product_id: i.json.product_id, product_title: i.json.title, model: i.json.model,
  url: '', source_page: '', found_via: '', doc_title: '', doc_type: '', label: '', evidence: '', fingerprint: '', file_url: '', mime: '', size_kb: 0,
  status: 'skipped', reason: i.json.skip, found_at: now } }));
```

## Step 9: Collect document links from the manufacturer's page

Most manufacturers either link their documents directly on the product page (as Ubiquiti does on `https://techspecs.ui.com/unifi/cameras-nvrs/uvc-g5-ptz`) or link to a dedicated support and download page for that model (as TP-LINK's `https://www.tp-link.com/au/home-networking/cloud-camera/tapo-c211/` links to `/au/support/download/tapo-c211/`). Following the product page plus up to two model-specific support pages costs nothing and took 7 to 14 seconds for five products in testing.

On the true branch of **`Has a model and domains?`**, add a Code node named **`Collect page links`** with **Mode** set to **Run Once for Each Item**. It uses a Code node because the second and third fetches depend on which support links appear on the first page, and it requires the model slug (`tapo-c211`) and the same locale (`/au/`) in the path so it never wanders onto support pages for other models or other regions:

```javascript
// Why Code: one product needs one to three page fetches, and which pages to follow depends on the first page's links.
const s = $('Find settings').first().json;
const p = $input.item.json;
if (!p.manufacturer_url) return { json: { ...p, page_links: [], pages_read: [] } };
const origin = u => (/^https?:\/\/[^\/?#]+/i.exec(u) || [''])[0];
const abs = (href, base) => {
  href = href.replace(/&amp;/g, '&').trim();
  if (/^https?:\/\//i.test(href)) return href;
  if (href.startsWith('//')) return 'https:' + href;
  if (href.startsWith('/')) return origin(base) + href;
  return base.replace(/[^\/]*([?#].*)?$/, '') + href;
};
const host = u => ((/^https?:\/\/([^\/:?#]+)/i.exec(u) || [])[1] || '').toLowerCase().replace(/^www\./, '');
const official = u => { const h = host(u); return !!h && p.domains.some(d => h === d || h.endsWith('.' + d)); };
const linksOf = (html, base) => [...html.matchAll(/<a\b[^>]*?href=["']([^"'#][^"']*)["'][^>]*>([\s\S]*?)<\/a>/gi)].map(m => ({
  url: abs(m[1], base),
  title: (((/aria-label=["']([^"']+)/i.exec(m[0]) || [])[1]) || m[2].replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ').trim().slice(0, 200)
}));
const get = async url => {
  try { return String(await this.helpers.httpRequest({ url, headers: { 'User-Agent': s.user_agent }, timeout: 20000, json: false })); }
  catch (e) { return ''; }
};
// Pages for this model only: the slug ("tapo-c211") in the path, and the same locale as the manufacturer page.
const slug = p.model.toLowerCase().replace(/\([^)]*\)/g, '').trim().replace(/[\s_]+/g, '-');
const locale = (/^https?:\/\/[^\/]+\/([a-z]{2}(?:-[a-z]{2})?)\//i.exec(p.manufacturer_url) || [])[1] || '';
const pages = [p.manufacturer_url], read = [], found = [];
while (pages.length && read.length < s.max_pages) {
  const url = pages.shift();
  const html = await get(url);
  read.push(url + (html ? '' : ' (no reply)'));
  for (const l of linksOf(html, url)) {
    if (!official(l.url)) continue;
    found.push({ ...l, source_page: url });
    const path = l.url.toLowerCase();
    if (s.follow_support_pages && path.includes(slug) && /support|download|document|resource|manual/.test(path)
        && (!locale || path.includes('/' + locale.toLowerCase() + '/'))
        && !read.some(r => r.startsWith(l.url)) && !pages.includes(l.url)) pages.push(l.url);
  }
}
return { json: { ...p, page_links: found, pages_read: read } };
```

## Step 10: Search for the rest (optional)

Sometimes a manufacturer splits its documents across domains or hides the datasheet off the regional support page. For the Tapo C211, TP-LINK's `/au/support/download/tapo-c211/` page only linked two generic family guides ("Tapo Camera_Quick Installation Guide(EU1_12 Languages)" and "Tapo App User Guide (for Tapo Indoor Outdoor Cameras)"), while the model-specific "Tapo C211 V3 Installation and User Guide" on `tapo.com` and the "Tapo C211 3.0&3.6 Datasheet" were found by adding one Google search.

When you turn on `use_search`, you might be tempted to add `site:tp-link.com OR site:tapo.com` to the search query, but DataForSEO bills more for a `site:` search. In testing, a search with `site:tp-link.com` cost US$0.0175 at 20 results against US$0.0035 without it, and wrapping the `site:` operator in brackets made Google ignore it and return results from other sites anyway. On a store I run, document searches with two `site:` operators averaged US$0.017 each, against US$0.003 for the rest. Searching plainly (`TP-LINK Tapo C211 user guide datasheet`) and filtering to `manufacturer_domains` in code costs one-fifth as much and catches files on sister domains like `tapo.com` and `vigi.com` in a single request.

Connect **`Collect page links`** to an If node named **`Search needed?`** with the condition `={{ $('Find settings').first().json.use_search && !$json.cached_results }}`. On the true branch, add **`Search the manufacturer's site`** (HTTP Request) with these settings:

| Setting | Value |
|---|---|
| Method | POST |
| URL | `https://api.dataforseo.com/v3/serp/google/organic/live/advanced` |
| Authentication | Generic Credential Type > Basic Auth |
| Settings > On Error | Continue |

Set the JSON body expression to:

```javascript
={{ JSON.stringify([{
  keyword: $json.query,
  location_name: $('Find settings').first().json.search_location,
  language_code: $('Find settings').first().json.language_code,
  depth: $('Find settings').first().json.search_depth
}]) }}
```

Connect **`Search the manufacturer's site`** to a Filter node named **`Search worked?`** (`={{ (($json.tasks || [])[0] || {}).status_code === 20000 }}`), followed by **`Save the search`** (Data table > Insert into `document_searches`, saving `query`, `product_id`, `results` as JSON of the organic `url`, `title` and `snippet`, `cost` and `fetched_at`). Checking for status `20000` before caching means that if DataForSEO returns a temporary upstream error, such as `"Internal SE Server Error."` (status `40101`), which came up several times during testing, the failed response is not cached in `document_searches`, and **`Remove the tag`** at the end of the lane leaves the `documents` tag on that product so the next run automatically retries the search.

## Step 11: Keep the right links and match the exact model

Both **`Search the manufacturer's site`** and the false branch of **`Search needed?`** connect to a Code node named **`Pick candidates`**. It combines the links from the manufacturer's page with any search results, follows DataForSEO's `google.com/goto` redirect wrappers to their real target URLs, unwraps PDF viewer links (`?file=https://...`), drops non-manufacturer domains and forum or staging subdomains, and filters out hub pages (`/support/`, `/downloads/`) and FAQ articles so only real candidate documents remain:

```javascript
// Document types, most specific first: a declaration of conformity often also says "user manual".
const TYPE_RULES = [
  ['compliance', /declaration of conformity|eu declaration|uk declaration|certificate of conformity|\bdoc\b.*conformity/i, /[_-]doc\.pdf|\/compliance\/|declaration|conformity/i],
  ['datasheet', /\bdata ?sheet\b|technical specifications|spec(ification)? sheet/i, /datasheet|data[_ -]sheet|[_-]ds\.pdf|\/ds\/|techspecs|spec[_ -]?sheet/i],
  ['setup', /quick (start|installation)|installation guide|setup guide|getting started/i, /qsg|qig|quick[_ -]?start|quick[_ -]?install|installation|setup[_ -]guide/i],
  ['manual', /user'?s? (guide|manual)|instruction manual|reference manual|owner'?s manual|operation manual/i, /user[_ -]?guide|user[_ -]?manual|[_-]ug[_.-]|manual/i],
];
const LABELS = { manual: 'User manual', setup: 'Setup guide', datasheet: 'Datasheet', compliance: 'Compliance document' };
const typeOf = (head, urlTitle) => {
  for (const [t, inText] of TYPE_RULES) if (head && inText.test(head)) return t;
  for (const [t, , inUrl] of TYPE_RULES) if (inUrl.test(urlTitle)) return t;
  return null;
};

// Model keys: the full model number first, then variants (no colour suffix, no family prefix).
const decode = t => { try { return decodeURIComponent(t); } catch (e) { return String(t || ''); } };
const modelKeys = (model, prefixes) => {
  const full = String(model || '').replace(/\([^)]*\)/g, '').trim();
  const keys = [full, full.replace(/[-\s](B|W|BK|WH|BLK|WHT|BLACK|WHITE)$/i, '')];
  for (const k of [...keys]) for (const p of prefixes) keys.push(k.replace(new RegExp('^' + p + '[\\s_-]+', 'i'), ''));
  return [...new Set(keys)].filter(k => k.length >= 4);
};
// Whole tokens only: "C211" never matches "C2110", and "Tapo C211" also matches "Tapo_C211" or "tapo-c211".
const findModel = (model, prefixes, text) => {
  const hay = decode(text);
  const keys = modelKeys(model, prefixes);
  for (const key of keys) {
    const tokens = key.match(/[a-z]+|\d+/gi) || [];
    if (!tokens.length) continue;
    const re = new RegExp('(^|[^a-z0-9])(' + tokens.join('[\\s_\\-]*') + ')(?=$|[^a-z0-9])', 'i');
    const m = re.exec(hay);
    if (!m) continue;
    // "VIGI C540-W" or "UACC-G5-PTZ-ICM": a hyphen and more characters make it another model.
    const after = hay.slice(m.index + m[0].length, m.index + m[0].length + 8);
    const longer = /^-[a-z0-9]/i.test(after) ? (m[2] + after.match(/^-[a-z0-9]+/i)[0]) : '';
    return { key, quote: m[2], variant: key !== keys[0], longer };
  }
  return null;
};

const s = $('Find settings').first().json;
const existing = new Set($('Read existing documents').all().map(i => i.json).filter(r => r.url).map(r => r.product_id + ' ' + r.url));
const host = u => ((/^https?:\/\/([^\/:?#]+)/i.exec(u) || [])[1] || '').toLowerCase().replace(/^www\./, '');
const direct = u => {
  let x = String(u || '').replace(/&amp;/g, '&');
  const m = /[?&]file=([^&]+)/i.exec(x);           // PDF viewer links: ?file=https://.../manual.pdf
  if (m) { const y = decode(m[1]); if (/^https?:\/\//i.test(y)) x = y; }
  return x.split('#')[0];
};
const DOC_WORDS = /manual|guide|datasheet|data[-_ ]sheet|spec(ification)?[-_ ]?sheet|quick[-_ ]?start|qsg|qig|install|declaration|conformity|[-_]ds\b|\/ds\//i;
const IS_FILE = /\.(pdf|docx?|zip)(\?|$)|\/document\/\d+|^https?:\/\/(dl|static|downloads?|docs?)\./i;
const SKIP = /\/(faq|faqs|blog|news|community|forum|press|careers|compare)\b|[?&](q|search)=/i;
const HUB = /\/(support|downloads?)\//i; // a download centre page lists documents; it isn't one
// A link counts when it has a document word and is either a file or names this model. Download centre pages and FAQ articles don't count.
// Generic category pages and FAQ articles don't count, however often they say "install".
const looksLikeDoc = (c, p) => {
  if (SKIP.test(c.url)) return false;
  const slug = p.model.toLowerCase().replace(/\([^)]*\)/g, '').trim().replace(/[\s_]+/g, '-');
  const names = c.url.toLowerCase().includes(slug) || !!findModel(p.model, s.family_prefixes, c.title);
  const words = DOC_WORDS.test(c.url + ' ' + c.title) || /techspecs/i.test(c.url);
  if (HUB.test(c.url) && !IS_FILE.test(c.url)) return false;
  return words && (IS_FILE.test(c.url) || names);
};
// DataForSEO returns some results as google.com/goto links: follow them to the real address.
const resolve = async url => {
  let u = url;
  for (let hop = 0; hop < 4 && /^https?:\/\/(www\.)?google\.[a-z.]+\/(goto|url)\?/i.test(u); hop++) {
    try {
      const r = await this.helpers.httpRequest({ url: u, method: 'GET', disableFollowRedirect: true, returnFullResponse: true,
        ignoreHttpStatusErrors: true, headers: { 'User-Agent': s.user_agent }, timeout: 15000 });
      const loc = (r.headers || {}).location;
      if (!loc) break;
      u = loc.startsWith('/') ? 'https://www.google.com' + loc : loc;
    } catch (e) { break; }
  }
  return u;
};
const out = [];
for (const [i, item] of $input.all().entries()) {
  // Two ways in: straight from Collect page links, or through the search (whose reply replaced the item).
  const p = item.json.product_id ? item.json : $('Collect page links').itemMatching(i).json;
  const raw = item.json.tasks ? (item.json.tasks[0] && item.json.tasks[0].result && item.json.tasks[0].result[0]
    ? item.json.tasks[0].result[0].items || [] : []).filter(r => r.type === 'organic').map(r => ({ url: r.url, title: r.title || '', snippet: r.description || '' }))
    : (p.cached_results || []);
  const results = [];
  for (const r of raw) results.push({ ...r, url: await resolve(r.url) });
  const all = [...p.page_links.map(l => ({ ...l, found_via: 'manufacturer page' })),
               ...results.map(r => ({ ...r, found_via: 'search', source_page: '' }))];
  const seen = new Set(), picked = [];
  for (const c of all) {
    const url = direct(c.url);
    const h = host(url);
    if (seen.has(url) || existing.has(p.product_id + ' ' + url)) continue;
    seen.add(url);
    if (!p.domains.some(d => h === d || h.endsWith('.' + d)) || /^(community|forum|forums|discuss|answers|uat|staging|stage|dev|test|beta)\./.test(h)) continue;
    if (!looksLikeDoc({ url, title: c.title }, p)) continue;
    picked.push({ ...c, url });
  }
  // PDFs first, then the manufacturer page's own links, capped per product.
  picked.sort((a, b) => (/\.pdf(\?|$)/i.test(b.url) - /\.pdf(\?|$)/i.test(a.url)) || (a.found_via === 'search') - (b.found_via === 'search'));
  for (const c of picked.slice(0, s.max_candidates)) out.push({ json: {
    product_id: p.product_id, product_title: p.title, model: p.model, url: c.url, doc_title: c.title,
    snippet: c.snippet || '', source_page: c.source_page || '', found_via: c.found_via
  }, pairedItem: { item: i } });
  if (!picked.length) out.push({ json: { product_id: p.product_id, product_title: p.title, model: p.model, url: '',
    status: 'skipped', reason: 'no new document links found (' + p.pages_read.length + ' pages read' + (s.use_search ? ', searched' : '') + ')' }, pairedItem: { item: i } });
}
return out;
```

Notice that the workflow never downloads or parses PDF files inside n8n. During early testing, reading camera manuals of 1 to 7 MB inside n8n froze the server and forced it to restart twice, because parsing multi-megabyte PDFs in memory can easily block a small n8n instance. Instead, each candidate link gets a lightweight `HEAD` request for its content type, file size and `ETag`, and only HTML guides are fetched as text.

Connect **`Pick candidates`** to an If node named **`Check it?`** (`={{ !!$json.url && !$json.status }}`, where the false branch carries `skipped` rows straight to **`Label and check`**), then on the true branch add **`Check the link`** (HTTP Request) with these settings:

| Setting | Value |
|---|---|
| Method | HEAD |
| URL | `={{ $json.url }}` |
| Header User-Agent | `={{ $('Find settings').first().json.user_agent }}` |
| Options > Timeout | 20000 |
| Options > Response > Include Response Headers and Status | On |
| Options > Response > Never Error | On |
| Settings > On Error | Continue |

After **`Check the link`**, connect a Code node named **`Read HTML guides`** so online HTML setup guides and spec pages have their text read while PDFs are left untouched:

```javascript
// Why Code: only the HTML links (online guides, spec pages) are read, and only their text is kept. PDFs are never downloaded here.
const s = $('Find settings').first().json;
const out = [];
for (const [i, item] of $input.all().entries()) {
  const ctype = String((item.json.headers || {})['content-type'] || '');
  let html = '';
  if (Number(item.json.statusCode) === 200 && /html/i.test(ctype)) {
    try {
      html = String(await this.helpers.httpRequest({ url: $('Pick candidates').itemMatching(i).json.url,
        headers: { 'User-Agent': s.user_agent }, timeout: 20000, json: false })).slice(0, 400000);
    } catch (e) { html = ''; }
  }
  out.push({ json: { ...item.json, html }, pairedItem: { item: i } });
}
return out;
```

The model-number matcher (`findModel`, used in both **`Pick candidates`** and **`Label and check`**) breaks the model into letter and digit tokens and requires whole-token boundaries (`(^|[^a-z0-9])...(?=$|[^a-z0-9])`). Because it matches whole tokens, a shared title like `"Tapo C210 (EU) 3.0/Tapo C211(EU)3.0/TC71(EU)3.0 Setup Guide"` matches the **Tapo C210** cleanly, while `C211` never matches `C2110` or `C210`. Just as importantly, `findModel` inspects the characters immediately after the match for a hyphen and further characters (`longer`):

- When checking the **TP-LINK VIGI C540**, the search returned `"VIGI C540-W(UN)1.0_datasheet"` and `"How to configure VIGI C540-4G"`. Even though `VIGI C540` is in the title, the matcher spots `-W` and `-4G` right after it and routes both to `review` with `"names VIGI C540-W: a different model?"` instead of publishing the Wi-Fi or 4G camera's datasheet on the wired camera's page.
- When checking the **Ubiquiti UniFi G5 PTZ** (`UVC-G5-PTZ`), a guide for one of its mount accessories lives at `dl.ui.com/qig/uacc-g5-ptz-icm`. Stripping the `UVC` prefix matches `G5-PTZ`, and the trailing `-icm` check catches `g5-ptz-icm` as a longer code and sends it to `review` (`"names g5-ptz-icm: a different model?"`) rather than marking it ready.

## Step 12: Label each document

Connect **`Read HTML guides`** (and the false branch of **`Check it?`**) to **`Label and check`** (Code). In this node, `TYPE_RULES` and `typeOf` classify the document (checking compliance phrases first so a declaration of conformity that mentions "user manual" is never mislabelled as a manual), `findModel` checks the URL, title and any HTML page text for the exact model number, the middle block records the HTTP `ETag` fingerprint and sets the row status (`ready`, `review` or `rejected`) with a human-readable `reason` and `evidence`, and the final loop automatically rejects generic family guides (such as `"Tapo Camera_Quick Installation Guide(EU1_12 Languages)"` on the C211 or the four general VIGI installation guides on the VIGI C540) whenever a document of the same type that explicitly names the model was already found:

```javascript
// Document types, most specific first: a declaration of conformity often also says "user manual".
const TYPE_RULES = [
  ['compliance', /declaration of conformity|eu declaration|uk declaration|certificate of conformity|\bdoc\b.*conformity/i, /[_-]doc\.pdf|\/compliance\/|declaration|conformity/i],
  ['datasheet', /\bdata ?sheet\b|technical specifications|spec(ification)? sheet/i, /datasheet|data[_ -]sheet|[_-]ds\.pdf|\/ds\/|techspecs|spec[_ -]?sheet/i],
  ['setup', /quick (start|installation)|installation guide|setup guide|getting started/i, /qsg|qig|quick[_ -]?start|quick[_ -]?install|installation|setup[_ -]guide/i],
  ['manual', /user'?s? (guide|manual)|instruction manual|reference manual|owner'?s manual|operation manual/i, /user[_ -]?guide|user[_ -]?manual|[_-]ug[_.-]|manual/i],
];
const LABELS = { manual: 'User manual', setup: 'Setup guide', datasheet: 'Datasheet', compliance: 'Compliance document' };
const typeOf = (head, urlTitle) => {
  for (const [t, inText] of TYPE_RULES) if (head && inText.test(head)) return t;
  for (const [t, , inUrl] of TYPE_RULES) if (inUrl.test(urlTitle)) return t;
  return null;
};

// Model keys: the full model number first, then variants (no colour suffix, no family prefix).
const decode = t => { try { return decodeURIComponent(t); } catch (e) { return String(t || ''); } };
const modelKeys = (model, prefixes) => {
  const full = String(model || '').replace(/\([^)]*\)/g, '').trim();
  const keys = [full, full.replace(/[-\s](B|W|BK|WH|BLK|WHT|BLACK|WHITE)$/i, '')];
  for (const k of [...keys]) for (const p of prefixes) keys.push(k.replace(new RegExp('^' + p + '[\\s_-]+', 'i'), ''));
  return [...new Set(keys)].filter(k => k.length >= 4);
};
// Whole tokens only: "C211" never matches "C2110", and "Tapo C211" also matches "Tapo_C211" or "tapo-c211".
const findModel = (model, prefixes, text) => {
  const hay = decode(text);
  const keys = modelKeys(model, prefixes);
  for (const key of keys) {
    const tokens = key.match(/[a-z]+|\d+/gi) || [];
    if (!tokens.length) continue;
    const re = new RegExp('(^|[^a-z0-9])(' + tokens.join('[\\s_\\-]*') + ')(?=$|[^a-z0-9])', 'i');
    const m = re.exec(hay);
    if (!m) continue;
    // "VIGI C540-W" or "UACC-G5-PTZ-ICM": a hyphen and more characters make it another model.
    const after = hay.slice(m.index + m[0].length, m.index + m[0].length + 8);
    const longer = /^-[a-z0-9]/i.test(after) ? (m[2] + after.match(/^-[a-z0-9]+/i)[0]) : '';
    return { key, quote: m[2], variant: key !== keys[0], longer };
  }
  return null;
};

const s = $('Find settings').first().json;
const excludes = s.exclude_patterns.map(x => new RegExp(x, 'i'));
const now = new Date().toISOString();
const rows = $input.all().map((item, i) => {
  const c = $('Pick candidates').itemMatching(i).json;
  const row = (extra) => ({ json: { product_id: c.product_id, product_title: c.product_title, model: c.model, url: c.url,
    source_page: c.source_page || '', found_via: c.found_via || '', doc_title: c.doc_title || '', found_at: now,
    doc_type: '', label: '', evidence: '', fingerprint: '', file_url: '', mime: '', size_kb: 0, ...extra }, pairedItem: { item: i } });
  if (c.status) return row({ status: c.status, reason: c.reason });

  const head = $('Check the link').itemMatching(i).json;
  const h = head.headers || {};
  const status = Number(head.statusCode || 0);
  if (status !== 200) return row({ status: 'rejected', reason: 'link failed (' + (status || (head.error || {}).message || 'no reply') + ')' });
  const mime = String(h['content-type'] || '').split(';')[0].toLowerCase();
  const sizeKb = Math.round(Number(h['content-length'] || 0) / 1024);
  // The same file behind five regional links has one ETag (or one size and date), so this is the duplicate check.
  const fileUrl = c.url;
  const fp = h.etag ? 'etag ' + h.etag : h['content-length'] ? mime + ' ' + h['content-length'] + ' ' + (h['last-modified'] || '') : '';
  const raw = String(item.json.html || '');
  const text = (raw ? raw.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>/gi, ' ').replace(/<[^>]+>/g, ' ') : raw)
    .replace(/&nbsp;|&#160;/g, ' ').replace(/\s+/g, ' ').trim();
  const title = (c.doc_title || decode(c.url.split('/').filter(Boolean).pop() || '')).replace(/\s+download$/i, '');
  const urlTitle = c.url + ' ' + title + ' ' + (c.snippet || '');
  const type = typeOf(text.slice(0, 1500), decode(urlTitle));
  const base = { doc_title: title.slice(0, 200), fingerprint: fp, file_url: fileUrl, mime, size_kb: sizeKb };

  if (excludes.some(re => re.test(urlTitle))) return row({ ...base, status: 'rejected', reason: 'matches exclude_patterns' });
  if (!type) return row({ ...base, status: 'rejected', reason: 'not a manual, setup guide, datasheet or compliance document' });
  if (type === 'compliance' && !s.include_compliance) return row({ ...base, status: 'rejected', reason: 'compliance documents are off' });

  const inName = findModel(c.model, s.family_prefixes, urlTitle);
  const inText = text.length >= 200 ? findModel(c.model, s.family_prefixes, text) : null;
  const typed = { ...base, doc_type: type, label: LABELS[type] };
  // A file that doesn't name the model may be a family guide that covers it: a person decides. A page we read that doesn't name it is out.
  if (!inName && !inText) return text.length >= 200
    ? row({ ...typed, status: 'rejected', reason: 'model not named in the link or the page' })
    : row({ ...typed, status: 'review', reason: 'model not named in the link: open the file to check it covers ' + c.model, evidence: 'linked from ' + (c.found_via === 'search' ? 'a search on the manufacturer site' : 'the manufacturer page') });

  // Ready only when the exact model number is in the link or title and the text (if any) doesn't disagree.
  let st = 'ready', why = '';
  const where = !inName ? 'in the page text' : decode(c.url).includes(inName.quote) ? 'in the link' : decode(title).includes(inName.quote) ? 'in the title' : 'in the search snippet';
  const ev = (inName || inText);
  if (!inName) { st = 'review'; why = 'model only in the page text (a family guide?)'; }
  else if (inName.longer) { st = 'review'; why = 'names ' + inName.longer + ': a different model?'; }
  else if (inName.variant) { st = 'review'; why = 'matched ' + inName.key + ', not the full model number ' + c.model; }
  else if (text.length >= 200 && !inText) { st = 'review'; why = 'model in the link but not on the page'; }
  if (s.review_mode === 'all' && st === 'ready') { st = 'review'; why = 'review_mode is all'; }
  if (s.review_mode === 'none' && st === 'review') st = 'ready';
  return row({ ...typed, status: st, reason: why, evidence: '"' + ev.quote + '" ' + where });
});
// A family guide (no model in its name) is only worth a look when nothing names the exact model for that type.
for (const r of rows) {
  const j = r.json;
  if (j.status !== 'review' || !/^model not named/.test(j.reason)) continue;
  const named = rows.find(x => x.json.product_id === j.product_id && x.json.doc_type === j.doc_type && x.json.status === 'ready');
  if (named) Object.assign(j, { status: 'rejected', reason: 'a ' + j.label.toLowerCase() + ' that names ' + j.model + ' was found' });
}
return rows;
```

Connect **`Label and check`** (along with **`Note skipped products`**) to **`Save the document`** (Data table > Upsert into `documents`, matching on `product_id` and `url`, mapping every column from the item).

![The documents data table for the VIGI C540, with labels, statuses and reasons](./_attachments/shopify-product-manuals/documents-data-table-rows.png "The VIGI C540's rows after review: what was published, what was rejected, and why.")

Finally, connect a second output from **`Build the product list`** to an HTTP Request node named **`Remove the tag`** placed below the main branch so it executes last. It removes the `documents` tag from every processed product except any product whose DataForSEO search failed, ensuring failed searches are retried on the next hourly run:

```javascript
={{ JSON.stringify({ query: (() => {
  // Keep the tag on products whose search failed, so the next run tries again.
  let failed = [];
  try {
    const asked = $('Search needed?').all(0);
    failed = $("Search the manufacturer's site").all().map((x, n) => (((x.json.tasks || [])[0] || {}).status_code === 20000 ? null : asked[n].json.product_id)).filter(Boolean);
  } catch (e) {}
  const ids = $('Build the product list').all().map(i => i.json.product_id).filter(id => !failed.includes(id));
  const tag = $('Find settings').first().json.queue_tag;
  return ids.length ? 'mutation Done {\n' + ids.map((id, n) => '  p' + n + ': tagsRemove(id: "gid://shopify/Product/' + id + '", tags: ["' + tag + '"]) { userErrors { message } }').join('\n') + '\n}' : '{ shop { id } }';
})() }) }}
```

## Step 13: Review the doubtful ones in Slack

When a candidate document does not name the exact model in its URL or title (such as `"Tapo App User Guide (for Tapo Indoor Outdoor Cameras)"` on the Tapo C211, or `"VIGI App_User Guide"`, `"VIGI Wired IPC_User Guide"` and `"VIGI Security Manager_User Guide"` on the VIGI C540), or when it names a longer model code like `"VIGI C540-W(UN)1.0_datasheet"`, **`Label and check`** sets its status to `review`. The **Review** lane bundles all `review` rows for a product into one Slack Block Kit card and handles signed button clicks using the same pattern covered in the [Slack approval workflow guide for n8n](https://www.reganmcgregor.com.au/slack-approval-workflow-n8n/).

Start the card-posting half of the Review lane with a schedule or manual trigger connected to **`Review settings`** (Edit Fields (Set) in JSON mode):

```json
{
  "slack_channel": "#review-documents",
  "store_handle": "your-store",
  "max_products": 10
}
```

Connect **`Get documents to review`** (Data table > Get from `documents` where `status` equals `review`), then add a Code node named **`Build the cards`** to group the rows by `product_id` and build one Slack card per product with **Change type**, **Approve**, **Reject** and **Open in Shopify** controls:

```javascript
const esc = t => String(t || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const TYPES = { manual: 'User manual', setup: 'Setup guide', datasheet: 'Datasheet', compliance: 'Compliance document' };
const card = (p, docs, adminUrl) => ({ blocks: [
  { type: 'section', text: { type: 'mrkdwn', text: '*' + esc(p.product_title) + '*\nModel ' + esc(p.model) + ': '
    + docs.length + ' document' + (docs.length === 1 ? '' : 's') + ' to check before they go on the product page.' } },
  ...docs.flatMap(d => {
    const open = d.status === 'review' || d.status === 'in_review';
    const name = esc(d.doc_title || decodeURIComponent(d.url.split('/').filter(Boolean).pop() || d.url)).slice(0, 120);
    const head = { type: 'section', text: { type: 'mrkdwn', text: '*<' + d.url + '|' + name + '>*\n' + d.label + ' · ' + esc(d.evidence)
      + (d.reason ? '\n_' + esc(d.reason) + '_' : '') } };
    if (open) head.accessory = { type: 'static_select', action_id: 'doc_type', placeholder: { type: 'plain_text', text: 'Change type' },
      options: Object.entries(TYPES).map(([v, t]) => ({ text: { type: 'plain_text', text: t }, value: d.id + ':' + v })) };
    return [{ type: 'divider' }, head, open
      ? { type: 'actions', elements: [
          { type: 'button', style: 'primary', text: { type: 'plain_text', text: 'Approve' }, action_id: 'doc_approve', value: String(d.id) },
          { type: 'button', style: 'danger', text: { type: 'plain_text', text: 'Reject' }, action_id: 'doc_reject', value: String(d.id) }] }
      : { type: 'context', elements: [{ type: 'mrkdwn', text: d.status === 'rejected' ? ':no_entry: ' + esc(d.reason) : ':white_check_mark: ' + esc(d.reason) }] }];
  }),
  { type: 'actions', elements: [{ type: 'button', text: { type: 'plain_text', text: 'Open in Shopify' }, action_id: 'link_admin',
    url: adminUrl }] }
] });
const s = $('Review settings').first().json;
const rows = $input.all().map(i => i.json).filter(r => r.id);
const byProduct = {};
for (const r of rows) (byProduct[r.product_id] = byProduct[r.product_id] || []).push(r);
return Object.values(byProduct).slice(0, s.max_products).map(docs => ({ json: {
  product_id: docs[0].product_id, ids: docs.map(d => d.id).slice(0, 10),
  card: card(docs[0], docs.slice(0, 10), 'https://admin.shopify.com/store/' + s.store_handle + '/products/' + docs[0].product_id), text: 'Documents to check: ' + docs[0].product_title } }));
```

Connect **`Post the card`** (HTTP Request, `POST https://slack.com/api/chat.postMessage`, **Predefined Credential Type > Slack API**, JSON body) with this body expression:

```javascript
={{ JSON.stringify({ channel: $('Review settings').first().json.slack_channel, text: $json.text, blocks: $json.card.blocks, unfurl_links: false, unfurl_media: false }) }}
```

After **`Post the card`**, connect a Code node named **`One row per document`** followed by **`Mark as in review`** (Data table > Update `documents` where `id` matches, setting `status` to `in_review`, `slack_channel` and `slack_ts`) so the same row is not posted twice:

```javascript
return $input.all().flatMap((item, i) => {
  const c = $('Build the cards').itemMatching(i).json;
  if (!item.json.ok) return [];
  return c.ids.map(id => ({ json: { id, slack_channel: item.json.channel, slack_ts: item.json.ts } }));
});
```

![The Slack review card for the TP-LINK VIGI C540 with Approve, Reject and Change type on each document](./_attachments/shopify-product-manuals/slack-review-card-vigi-c540.png "The review card for the TP-LINK VIGI C540: two datasheets and a guide for lookalike models, and a family app guide.")

For the interactive click path, add **`Slack button click`** (Webhook, `POST`, path `product-documents-review`, **Respond: Using 'Respond to Webhook' Node**, **Options > Raw Body** turned on) connected immediately to **`Respond to Slack`** (Respond to Webhook, **No Data**) so Slack gets an HTTP 200 within three seconds. Connect **`Read the click`** (Code) next to parse the form-encoded payload, reject timestamps older than five minutes, ignore clicks on the external **Open in Shopify** link, and assemble the string for HMAC verification:

```javascript
const raw = (await this.helpers.getBinaryDataBuffer(0, 'data')).toString('utf8');
const h = $input.first().json.headers;
if (Math.abs(Date.now() / 1000 - Number(h['x-slack-request-timestamp'])) > 300) throw new Error('Stale request');
const field = raw.split('&').find(kv => kv.startsWith('payload=')) || ''; // no URLSearchParams in the Code node
const b = JSON.parse(decodeURIComponent(field.slice(8).replace(/\+/g, ' ')));
const a = b.actions[0];
if (!/^doc_/.test(a.action_id)) return []; // Open in Shopify is a link: nothing to do
// The card's own Open in Shopify link, so the redrawn card keeps it.
const admin = ((b.message.blocks || []).flatMap(x => x.elements || []).find(e => e.action_id === 'link_admin') || {}).url || '';
const picked = a.action_id === 'doc_type' ? a.selected_option.value.split(':') : [a.value, ''];
return [{ json: {
  base: `v0:${h['x-slack-request-timestamp']}:${raw}`, expected: h['x-slack-signature'],
  action: a.action_id.replace('doc_', ''), id: Number(picked[0]), new_type: picked[1],
  user: b.user.username, channel: b.channel.id, ts: b.message.ts, admin_url: admin
} }];
```

Connect **`Sign the request`** (Crypto node, `HMAC`, `SHA256`, Value `{{ $json.base }}`, Property Name `sig`, Encoding `hex`, using a Crypto credential holding your Slack signing secret) and **`Signature valid?`** (If node with condition `={{ 'v0=' + $json.sig === $json.expected }}`). On the true branch, add **`Get the document`** (Data table > Get from `documents` where `id` equals the clicked row ID and `status` equals `in_review`, **Limit 1**), which ensures a double click or a click on an already-decided document finds nothing and stops cleanly.

Connect **`Save the decision`** (Data table > Update where `id` matches) with these field expressions:

| Setting | Value |
|---|---|
| `status` | `={{ (() => { const c = $('Read the click').first().json; return { approve: 'ready', reject: 'rejected', type: 'in_review' }[c.action]; })() }}` |
| `doc_type` | `={{ $('Read the click').first().json.new_type \|\| $json.doc_type }}` |
| `label` | `={{ { manual: 'User manual', setup: 'Setup guide', datasheet: 'Datasheet', compliance: 'Compliance document' }[$('Read the click').first().json.new_type \|\| $json.doc_type] }}` |
| `reason` | `={{ (() => { const c = $('Read the click').first().json; return c.action === 'approve' ? 'Approved by @' + c.user : c.action === 'reject' ? 'Rejected by @' + c.user : $json.reason; })() }}` |

To update the Slack message in place and immediately publish approved documents, connect **`Get the card's documents`** (Data table > Get where `slack_ts` equals the clicked card's `ts`, **Execute Once**), followed by **`Redraw the card`** (Code):

```javascript
const esc = t => String(t || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const TYPES = { manual: 'User manual', setup: 'Setup guide', datasheet: 'Datasheet', compliance: 'Compliance document' };
const card = (p, docs, adminUrl) => ({ blocks: [
  { type: 'section', text: { type: 'mrkdwn', text: '*' + esc(p.product_title) + '*\nModel ' + esc(p.model) + ': '
    + docs.length + ' document' + (docs.length === 1 ? '' : 's') + ' to check before they go on the product page.' } },
  ...docs.flatMap(d => {
    const open = d.status === 'review' || d.status === 'in_review';
    const name = esc(d.doc_title || decodeURIComponent(d.url.split('/').filter(Boolean).pop() || d.url)).slice(0, 120);
    const head = { type: 'section', text: { type: 'mrkdwn', text: '*<' + d.url + '|' + name + '>*\n' + d.label + ' · ' + esc(d.evidence)
      + (d.reason ? '\n_' + esc(d.reason) + '_' : '') } };
    if (open) head.accessory = { type: 'static_select', action_id: 'doc_type', placeholder: { type: 'plain_text', text: 'Change type' },
      options: Object.entries(TYPES).map(([v, t]) => ({ text: { type: 'plain_text', text: t }, value: d.id + ':' + v })) };
    return [{ type: 'divider' }, head, open
      ? { type: 'actions', elements: [
          { type: 'button', style: 'primary', text: { type: 'plain_text', text: 'Approve' }, action_id: 'doc_approve', value: String(d.id) },
          { type: 'button', style: 'danger', text: { type: 'plain_text', text: 'Reject' }, action_id: 'doc_reject', value: String(d.id) }] }
      : { type: 'context', elements: [{ type: 'mrkdwn', text: d.status === 'rejected' ? ':no_entry: ' + esc(d.reason) : ':white_check_mark: ' + esc(d.reason) }] }];
  }),
  { type: 'actions', elements: [{ type: 'button', text: { type: 'plain_text', text: 'Open in Shopify' }, action_id: 'link_admin',
    url: adminUrl }] }
] });
const docs = $input.all().map(i => i.json).sort((a, b) => a.id - b.id);
return [{ json: { blocks: card(docs[0], docs, $('Read the click').first().json.admin_url).blocks,
  text: 'Documents to check: ' + docs[0].product_title, product_id: docs[0].product_id,
  approved: $('Read the click').first().json.action === 'approve' } }];
```

Connect **`Redraw the card`** to **`Update the card`** (HTTP Request to `https://slack.com/api/chat.update`), then **`Approved?`** (If `={{ $('Redraw the card').first().json.approved }}`), and finally **`Send to Publish lane`** (Execute Workflow, **Source: Database**, Workflow `{{ $workflow.id }}`, passing `product_id` with **Wait for Sub-Workflow** turned off).

## Step 14: Upload the PDFs and fill the Documents table

The **Publish** lane starts from three triggers (`When Executed by Another Workflow` receiving `product_id`, `Every 10 minutes (Publish)` and `Run Publish now`), all connected to **`Publish settings`** (Edit Fields (Set) in JSON mode):

```json
{
  "store_domain": "your-store.myshopify.com",
  "namespace": "custom",
  "documents_key": "documents",
  "metaobject_type": "product_document",
  "host_files": true,
  "dry_run": true,
  "max_products": 10,
  "max_documents": 8,
  "max_per_type": 1,
  "max_file_mb": 20,
  "preferred_locales": [
    "/au/",
    "/en-au/",
    "/en/"
  ],
  "slack_channel": "#review-documents"
}
```

Notice that `dry_run` ships `true` so you can inspect the planned rows on your first run before anything is uploaded or written to Shopify. Connect **`Get all documents`** (Data table > Get all rows of `documents`, **Execute Once**), followed by a Code node named **`Plan the documents`**. When the same PDF sits behind multiple regional URLs (such as `/au/` and `/uk/`), it has the same `fingerprint` (`ETag`), so **`Plan the documents`** keeps the URL matching your `preferred_locales` first, caps each document type at `max_per_type: 1` so two rows that both read "Tapo C211 setup guide" never appear together, and decides whether each row needs `upload`, `check`, `link` (for HTML guides or PDFs over 20 MB) or `keep` (already published):

```javascript
const s = $('Publish settings').first().json;
let only = '';
try { only = String($('When Executed by Another Workflow').first().json.product_id || ''); } catch (e) {}
const rows = $input.all().map(i => i.json).filter(r => r.id && r.url);
const live = ['ready', 'uploading', 'published'];
const order = { manual: 0, setup: 1, datasheet: 2, compliance: 3 };
const rank = u => { const i = s.preferred_locales.findIndex(l => u.toLowerCase().includes(l)); return i < 0 ? 99 : i; };
const byProduct = {};
for (const r of rows) if (live.includes(r.status)) (byProduct[r.product_id] = byProduct[r.product_id] || []).push(r);
const todo = Object.keys(byProduct).filter(id => (!only || id === only) && byProduct[id].some(r => r.status !== 'published')).slice(0, s.max_products);
return todo.map(id => {
  // One copy of each file: the same fingerprint at another URL is a duplicate. Your preferred locale wins, then the oldest row.
  const docs = byProduct[id].slice().sort((a, b) => (a.status === 'published' ? -1 : 0) - (b.status === 'published' ? -1 : 0) || rank(a.url) - rank(b.url) || a.id - b.id);
  const seen = new Set(), keep = [], drop = [];
  for (const d of docs) { const k = d.fingerprint || d.url; if (seen.has(k)) drop.push(d); else { seen.add(k); keep.push(d); } }
  keep.sort((a, b) => order[a.doc_type] - order[b.doc_type] || (a.status === 'published' ? -1 : 0) - (b.status === 'published' ? -1 : 0) || rank(a.url) - rank(b.url) || a.id - b.id);
  // One of each type by default: two "setup guide" rows with the same title help nobody.
  const perType = {};
  for (const d of keep.splice(0)) { perType[d.doc_type] = (perType[d.doc_type] || 0) + 1; (perType[d.doc_type] <= s.max_per_type ? keep : drop).push(d); }
  return { json: { product_id: id, product_gid: 'gid://shopify/Product/' + id,
    docs: keep.slice(0, s.max_documents).map(d => ({ ...d,
      action: d.status === 'published' ? 'keep' : (!s.host_files || !/pdf/i.test(d.mime) || d.size_kb > s.max_file_mb * 1024) ? 'link' : d.file_id ? 'check' : 'upload' })),
    duplicates: drop.map(d => d.id), over_limit: keep.slice(s.max_documents).map(d => d.id) } };
});
```

Connect **`Dry run?`** (If `={{ $('Publish settings').first().json.dry_run }}`), where `true` stops at **`Stop: dry run`** (No Operation) and `false` continues to **`Get Shopify token for Publish`** and **`Upload and check files`** (Code).

Shopify's `fileCreate` mutation processes remote files asynchronously: on the first run it returns a file ID with status `PROCESSING` (and links any HTML guides right away), and a minute later on the next run the file status becomes `READY` with its permanent CDN URL. Also, some manufacturers serve downloads from extensionless redirect URLs like `tp-link.com/document/42483/`, which caused Shopify to name the file `42483` in early testing; **`Upload and check files`** follows up to five `HEAD` redirects to reach the real `.pdf` URL and passes a clean `filename` (`tapo-c211-user-manual.pdf`) to `fileCreate`:

```javascript
// Why Code: a file goes through create, then PROCESSING, then READY over several runs, and each document's next step depends on that state.
const s = $('Publish settings').first().json;
const token = $('Get Shopify token for Publish').first().json.access_token;
const gqlCall = async (query, variables) => {
  const r = await this.helpers.httpRequest({ method: 'POST', url: 'https://' + s.store_domain + '/admin/api/2026-10/graphql.json',
    headers: { 'X-Shopify-Access-Token': token }, body: { query, variables }, json: true, timeout: 45000 });
  if (r.errors && r.errors.length) throw new Error(r.errors.map(e => e.message).join('; '));
  return r.data;
};
const out = [];
for (const item of $('Plan the documents').all()) {
  const p = item.json;
  for (const d of p.docs) {
    try {
      if (d.action === 'upload') {
        // Shopify names the file after the address, so follow redirects to the real .pdf (a /document/42483/ link has no extension).
        let src = d.file_url || d.url;
        for (let hop = 0; hop < 5; hop++) {
          const r = await this.helpers.httpRequest({ url: src, method: 'HEAD', disableFollowRedirect: true, returnFullResponse: true,
            ignoreHttpStatusErrors: true, timeout: 20000 });
          const loc = (r.headers || {}).location;
          if (!loc || r.statusCode < 300 || r.statusCode >= 400) break;
          src = loc.startsWith('/') ? (/^https?:\/\/[^\/]+/i.exec(src) || [''])[0] + loc : loc;
        }
        src = src.replace(/ /g, '%20');
        const ext = (/\.(pdf|docx?|zip)(?:$|[?#])/i.exec(src) || [])[1];
        const name = (d.model + ' ' + d.label).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') + (ext ? '.' + ext.toLowerCase() : '');
        const x = await gqlCall(`mutation Upload($files: [FileCreateInput!]!) {
          fileCreate(files: $files) { files { id fileStatus } userErrors { field message } } }`,
          { files: [Object.assign({ originalSource: src, contentType: 'FILE', alt: (d.model + ' ' + d.label).slice(0, 512) }, ext ? { filename: name } : {})] });
        const err = x.fileCreate.userErrors.map(e => e.message).join('; ');
        if (err || !x.fileCreate.files[0]) { d.result = 'failed'; d.error = err || 'no file returned'; continue; }
        d.file_id = x.fileCreate.files[0].id; d.uploaded_at = new Date().toISOString(); d.action = 'check';
      }
      if (d.action === 'check') {
        const x = await gqlCall(`query File($id: ID!) { node(id: $id) { ... on GenericFile { fileStatus url fileErrors { message } } } }`, { id: d.file_id });
        const f = x.node || {};
        if (f.fileStatus === 'READY' && f.url) { d.result = 'ready'; d.link = f.url; }
        else if (f.fileStatus === 'FAILED') { d.result = 'failed'; d.error = (f.fileErrors || []).map(e => e.message).join('; ') || 'Shopify could not process the file'; }
        else if (d.uploaded_at && Date.now() - Date.parse(d.uploaded_at) > 24 * 3600 * 1000) { d.result = 'failed'; d.error = 'not READY after 24 hours'; }
        else d.result = 'pending';
      }
      if (d.action === 'link') { d.result = 'ready'; d.link = d.url; d.file_id = ''; }
      if (d.action === 'keep') d.result = 'keep';
    } catch (e) { d.result = 'failed'; d.error = String(e.message || e).slice(0, 300); }
  }
  out.push({ json: p });
}
return out;
```

![Content > Files with the uploaded PDFs named by model and type](./_attachments/shopify-product-manuals/shopify-files-pdfs.png "PDFs uploaded to Shopify Files with clean model-and-type filenames.")

Connect **`Write the document entries`** (HTTP Request) to upsert every `ready` document for a product in a single GraphQL call using a stable handle (`doc-<id>`) so re-running never creates duplicate metaobjects:

```javascript
={{ JSON.stringify((() => {
  const s = $('Publish settings').first().json;
  const docs = $json.docs.filter(d => d.result === 'ready');
  if (!docs.length) return { query: '{ shop { id } }', variables: {} };
  const q = 'mutation Entries(' + docs.map((d, n) => '$h' + n + ': MetaobjectHandleInput!, $m' + n + ': MetaobjectUpsertInput!').join(', ') + ') {\n'
    + docs.map((d, n) => '  d' + n + ': metaobjectUpsert(handle: $h' + n + ', metaobject: $m' + n + ') { metaobject { id } userErrors { field message } }').join('\n') + '\n}';
  const v = {};
  docs.forEach((d, n) => {
    v['h' + n] = { type: s.metaobject_type, handle: 'doc-' + d.id };
    v['m' + n] = { fields: [
      { key: 'title', value: d.model + ' ' + d.label.toLowerCase() },
      { key: 'document_type', value: d.label },
      { key: 'url', value: d.link },
      { key: 'source_url', value: d.url },
      { key: 'model', value: d.model },
      ...(d.file_id ? [{ key: 'file', value: d.file_id }] : [])
    ] };
  });
  return { query: q, variables: v };
})()) }}
```

Next, connect **`Set the Documents field`** (HTTP Request) to write the complete ordered list of metaobject IDs, combining any entries already on the product (`keep`) with the newly created ones (`ready`), to `custom.documents`:

```javascript
={{ JSON.stringify((() => {
  const s = $('Publish settings').first().json;
  const p = $('Upload and check files').item.json;
  const data = $json.data || {};
  const fresh = p.docs.filter(d => d.result === 'ready').map((d, n) => (data['d' + n] && data['d' + n].metaobject || {}).id);
  let i = 0;
  // The whole list, in the planned order: entries already on the page, plus the ones written just now.
  const ids = p.docs.map(d => d.result === 'keep' ? d.metaobject_id : d.result === 'ready' ? fresh[i++] : null).filter(Boolean);
  if (!ids.length) return { query: '{ shop { id } }' };
  return { query: 'mutation Set($m: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $m) { metafields { id } userErrors { field message } } }',
    variables: { m: [{ ownerId: p.product_gid, namespace: s.namespace, key: s.documents_key, type: 'list.metaobject_reference', value: JSON.stringify(ids) }] } };
})()) }}
```

Connect **`Record the results`** (Code) and **`Save the results`** (Data table > Update where `id` matches, updating `status`, `reason`, `file_id`, `metaobject_id`, `uploaded_at` and `published_at`) so rows waiting on Shopify processing become `uploading`, completed rows become `published`, and regional or same-type extras are marked `duplicate`:

```javascript
const now = new Date().toISOString();
const out = [];
$input.all().forEach((item, i) => {
  const p = $('Upload and check files').itemMatching(i).json;
  const entries = $('Write the document entries').itemMatching(i).json.data || {};
  const setErr = ((item.json.data || {}).metafieldsSet || {}).userErrors || [];
  let n = 0;
  for (const d of p.docs) {
    if (d.result === 'keep') continue;
    const row = { id: d.id, file_id: d.file_id || '', uploaded_at: d.uploaded_at || null };
    if (d.result === 'ready') {
      const e = entries['d' + n++] || {};
      const err = (e.userErrors || []).map(x => x.message).concat(setErr.map(x => x.message)).join('; ');
      Object.assign(row, err || !e.metaobject ? { status: 'failed', reason: err || 'entry not written' }
        : { status: 'published', metaobject_id: e.metaobject.id, published_at: now, reason: /^Approved by/.test(d.reason || '') ? d.reason : '' });
    } else if (d.result === 'pending') Object.assign(row, { status: 'uploading', reason: 'waiting for Shopify to process the file' });
    else Object.assign(row, { status: 'failed', reason: d.error });
    out.push({ json: Object.assign({ metaobject_id: d.metaobject_id || '', published_at: d.published_at || null, product_title: d.product_title }, row) });
  }
  for (const id of p.duplicates) out.push({ json: { id, status: 'duplicate', reason: 'same file, or another of the same type is shown', file_id: '', metaobject_id: '', uploaded_at: null, published_at: null } });
});
return out;
```

Finish the Publish lane with **`Anything to report?`** (If node with **Execute Once** turned on and condition `={{ $('Record the results').all().some(i => ['published', 'failed'].includes(i.json.status)) }}`), connected to **`Post the summary`** (HTTP Request to `https://slack.com/api/chat.postMessage`):

```javascript
={{ JSON.stringify((() => {
  const r = $('Record the results').all().map(i => i.json);
  const pub = r.filter(x => x.status === 'published'), wait = r.filter(x => x.status === 'uploading'), bad = r.filter(x => x.status === 'failed');
  const names = xs => [...new Set(xs.map(x => x.product_title).filter(Boolean))].slice(0, 8).join(', ');
  return { channel: $('Publish settings').first().json.slack_channel, unfurl_links: false,
    text: ':page_facing_up: Product documents: ' + pub.length + ' published' + (pub.length ? ' (' + names(pub) + ')' : '')
      + (wait.length ? '\n' + wait.length + ' waiting for Shopify to process the file' : '')
      + (bad.length ? '\n:warning: ' + bad.length + ' failed: ' + bad.slice(0, 5).map(x => (x.product_title || x.id) + ': ' + x.reason).join('; ') : '') };
})()) }}
```

## What it costs

If your products have their manufacturer page URL populated and you keep `use_search` set to `false`, the entire workflow costs nothing beyond your existing n8n instance. Because matching and labelling use deterministic rules in code, there are no AI token costs at any catalogue size, and caching search results in `document_searches` for 30 days means DataForSEO is only billed once per product when `use_search` is turned on.

| Item | 500 products | 2,000 products | 10,000 products |
|---|---|---|---|
| n8n | Free self-hosted; or [n8n Cloud](https://n8n.io/pricing/) (check current plan, checked November 2026) | Free self-hosted; or n8n Cloud | Free self-hosted; or n8n Cloud |
| Shopify Files and Metaobjects | Included in your Shopify plan | Included in your Shopify plan | Included in your Shopify plan |
| DataForSEO (`use_search: false`) | US$0 | US$0 | US$0 |
| DataForSEO (`use_search: true`, US$0.0035/search at 20 results) | ~US$1.75 one-off (then new products only) | ~US$7.00 one-off (then new products only) | ~US$35.00 one-off (then new products only) |
| AI model | US$0 (no AI model used) | US$0 (no AI model used) | US$0 (no AI model used) |

Compared with attachment apps (which run from free to US$19.99 a month, checked November 2026), the apps are simpler if you already have every PDF in a folder on your desktop, whereas the n8n workflow solves the actual bottleneck for multi-brand stores: finding, checking and naming the manufacturer's files automatically. Four settings in **`Find settings`** control what you spend: `use_search` (turn it on only when manufacturer page links are not enough), `search_depth` (10 results is cheaper than 20), `cache_days` (how long search results are reused) and `batch_size` (how many tagged products run per hour). Leaving `site:` out of the query and filtering domains in code keeps each 20-result search at US$0.0035 instead of US$0.0175.

## Common mistakes

### Labelling a declaration of conformity as the user manual

A declaration of conformity often sits in the same download list as the manual and carries the same model number, so a rule that checks for "manual" first can publish a one-page legal certificate as the product's user manual. Always test compliance phrases (`declaration of conformity`, `certificate of conformity`, `-doc.pdf`) before datasheet, setup guide and manual rules, as `TYPE_RULES` does in **`Label and check`**.

### Attaching an accessory's guide because it names the product

A mounting bracket or power adapter guide, such as `uacc-g5-ptz-icm` for the Ubiquiti UniFi G5 PTZ (`UVC-G5-PTZ`), often includes the camera's model code inside a longer part number. Checking whether the matched model code is immediately followed by a hyphen and another token (`longer`) catches accessory codes and sends them to Slack review instead of publishing them on the main product.

### Matching a lookalike model

A simple substring check matches `C211` inside `C2110` and treats `VIGI C540-W` or `VIGI C540-4G` as a match for the wired `VIGI C540`. Requiring whole-token boundaries around the model tokens and flagging any trailing `-W` or `-4G` suffix stops lookalike models from polluting your product page.

### Five regional copies of one datasheet in the table

Global manufacturers frequently publish the exact same PDF under `/au/`, `/uk/`, `/us/` and `/eu/` paths. Recording the HTTP `ETag` (or content length and `Last-Modified` header) during the `HEAD` check and sorting by `preferred_locales` in **`Plan the documents`** drops regional duplicates before anything is uploaded.

### Trusting a retailer's, forum's or manual site's copy of a PDF

Third-party manual directories and competitor stores often host outdated hardware revisions or watermarked scans. Restricting every link and search result to `manufacturer_domains` (and blocking `community.` or `forum.` subdomains) ensures every file comes straight from the brand that made the product.

### Parsing PDFs inside n8n

Downloading and extracting text from multi-megabyte PDFs inside an n8n workflow can exhaust memory and freeze a small n8n server (it caused two server restarts during testing for this guide). Send a `HEAD` request to PDFs and only fetch page text when the `Content-Type` header is HTML.

### Linking a file before Shopify says READY, or uploading from an address with no file extension

Shopify's `fileCreate` mutation returns a `PROCESSING` status before the CDN URL exists, and passing an extensionless redirect URL like `/document/42483/` makes Shopify save the file as `42483` without `.pdf`. Follow redirects with `HEAD` requests to find the `.pdf` extension, pass a clean `filename` (`tapo-c211-user-manual.pdf`), and wait until a subsequent check confirms `fileStatus === 'READY'` before writing the metaobject entry.

### Paying five times as much for site: searches

Adding `site:tp-link.com` to a DataForSEO query raises the cost of a 20-result search from US$0.0035 to US$0.0175, and grouping multiple `site:` operators in brackets causes Google to ignore them. Run a plain `<vendor> <model> user guide datasheet` query and filter to your manufacturer domains in JavaScript.

## Make it your own

### Other industries

The same `product_document` metaobject and n8n workflow work for any store where buyers rely on official documents before or after purchase, including safety data sheets (SDS) for chemicals and cosmetics, assembly instructions for flat-pack furniture, care guides for apparel, and warranty cards for appliances. Update the `choices` list on `document_type` in **`Create the document type`** and add your industry's keywords to `TYPE_RULES` in **`Pick candidates`** and **`Label and check`**.

### Own-brand products

If you manufacture your own products alongside third-party brands, you can upload your own PDFs in **Content > Files** and attach them to the same `custom.documents` field on your own-brand products. The Liquid table in Step 5 renders manual and automated entries identically.

### Use the documents elsewhere

While this workflow's job is putting manuals and spec sheets on the product page, the HTML guide text and document metadata that the **Find** lane collects in `documents` can also serve as one optional input when you generate product FAQs, compatible accessory links, product descriptions or structured specification tables. Those workflows stand on their own without this table, so you can plug the document rows in later if you build them.

### A product database instead of searching

If you subscribe to a structured catalogue feed such as [Icecat](https://icecat.biz/) that already maps GTINs or barcodes to official manual and datasheet URLs, you can replace **`Collect page links`** and **`Search the manufacturer's site`** with a single HTTP Request to that catalogue API while keeping the same **`Check the link`**, **`Label and check`** and **Publish** nodes.

### Downloads for logged-in customers only (B2B)

Wholesale and trade stores sometimes restrict technical manuals or compliance certificates to approved trade accounts. To hide the table from guests, wrap the Custom Liquid snippet from Step 5 in `{%- if customer -%} ... {%- endif -%}` (or add an `{%- else -%}` prompt asking the visitor to sign in to view technical documentation).

## FAQ

### Can I host a manufacturer's manual on my store?

Manufacturers publish user manuals, setup guides and datasheets so prospective buyers and owners can use their products safely, and authorised resellers routinely link or host those PDFs on product pages. Check your reseller agreement if a brand has specific distribution terms, and if you prefer not to host copies on your own CDN, set `host_files: false` in **`Publish settings`** so the table links directly to the manufacturer's URL.

### Does Google index PDFs on a Shopify store?

Yes, [Google indexes PDF files](https://developers.google.com/search/docs/crawling-indexing/indexable-file-types) and can show them in search results. Even so, your product page is the page that can actually convert a shopper, which is why presenting the PDFs in a structured table on the product page is much more valuable than hoping a raw PDF ranks on its own.

### Will it work without model numbers?

Not reliably, because telling the right manual apart from a lookalike model (`VIGI C540` vs `VIGI C540-W`) depends on matching the exact model code. Fill in the `Model number (MPN)` metafield (`custom.mpn`) on your products, or keep `use_sku_if_no_mpn: true` if your variant SKUs are the manufacturer's model numbers.

### How often should it run?

You only need to run the **Find** lane once for each new product when you add it to your catalogue, and then every few months if you want to check for updated hardware revisions or new datasheets. Whenever you want the workflow to re-check a product, add the `documents` tag to that product in Shopify.

To get started, run the **Setup** lane once, add your brands' domains to `manufacturer_domains` in **`Find settings`**, tag five products with `documents`, and inspect the resulting rows in the `documents` Data Table while `dry_run` is still `true` in **`Publish settings`**. Once you are happy with the matches, switch `dry_run` to `false` and let **Publish** upload the PDFs and populate your product pages.

<TemplateCallout
  repo="https://github.com/reganmcgregor/n8n-ecommerce-templates/tree/main/product-manuals-spec-sheets"
>

- Finds each product's manuals, setup guides, datasheets and compliance documents on the manufacturer's own site.
- Checks the model number and the document type in code, and asks in Slack only when it isn't sure.
- Uploads PDFs to Shopify Files and fills a Documents table on the product page.

</TemplateCallout>
