> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/web/get-started/samples/webviewer-user-bookmarks-nodejs.md).

# Enable Bookmark Saving and Loading with Node.js and WebViewer

Sample WebViewer project with a Node.js backend that enables save/load user bookmarks.

{% hint style="info" %}
**Requirements**

*These packages are required to use these features in production. Trial keys have unlimited access to all features*

<a href="/web/get-started/readme.md" class="button primary">Web SDK</a><a href="https://apryse.com/capabilities#PageManipulation" class="button primary">Package: Page Manipulation</a>
{% endhint %}

This sample demonstrates how to implement WebViewer with a Node.js backend and enable save and load user bookmarks.

WebViewer provides a slick out-of-the-box responsive UI that enables you to view, annotate and manipulate PDFs and other document types inside any web project.

For [detailed install instructions, please follow our guide.](/web/outlines-bookmarks/user-bookmarks.md#prerequisites)

Click the button below to view the full project in GitHub.

{% tabs %}
{% tab title="index.js" %}
{% code title="index.js" lineNumbers="true" %}

```js
var viewerElement = document.getElementById('viewer');
var DOCUMENT_ID = 'webviewer-demo-1';

WebViewer({
  path: 'lib',
  initialDoc: './webviewer-demo.pdf',
  // ui: 'legacy',
}, viewerElement).then((instance) => {

  instance.UI.addEventListener('userBookmarksChanged', (bookmarks) => {
    const bookmarksString = JSON.stringify(bookmarks);
    saveBookmarksString(DOCUMENT_ID, bookmarksString).then(() => {
      console.log('Bookmarks saved successfully.');
    });
  });

  const onSaveBookmarks = () => {
    const bookmarks = instance.UI.exportBookmarks();
    const bookmarksString = JSON.stringify(bookmarks);
    saveBookmarksString(DOCUMENT_ID, bookmarksString).then(() => {
      alert('Bookmarks saved successfully.');
    });
  };

  /** Legacy UI: Uncomment this to add a save button to the header */
  // instance.UI.enableElements(['bookmarksPanel', 'bookmarksPanelButton']);
  // instance.UI.setHeaderItems((header) => {
  //   header.push({
  //     type: 'actionButton',
  //     img: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/></svg>',
  //     onClick: onSaveBookmarks,
  //   });
  // });
  /** End of Legacy UI */


  /** Modular UI: Add a save button to the header */
  // Comment this out on legacy UI
  const saveButton = new instance.UI.Components.CustomButton({
    dataElement: 'customButton',
    title: 'Save Bookmarks',
    onClick: onSaveBookmarks,
    img: 'icon-save',
  });
  const defaultHeader = instance.UI.getModularHeader('default-top-header');
  defaultHeader.setItems([...defaultHeader.getItems(), saveButton]);
  /** End of Modular UI */


  // Load bookmarks when document is loaded
  instance.Core.documentViewer.addEventListener('documentLoaded', () => {
    loadBookmarksString(DOCUMENT_ID).then((bookmarksString = '') => {
      const bookmarks = JSON.parse(bookmarksString);
      instance.UI.importBookmarks(bookmarks);
    });
  });
});


// Make a POST request with bookmarks string
const saveBookmarksString = (documentId, bookmarksString) => {
  return new Promise((resolve) => {
    fetch(`/server/bookmarksHandler.js?documentId=${documentId}`, {
      method: 'POST',
      body: bookmarksString
    }).then((response) => {
      if (response.status === 200) {
        resolve();
      }
    });
  });
};

// Make a GET request to get bookmarks string
const loadBookmarksString = (documentId) => {
  return new Promise((resolve) => {
    fetch(`/server/bookmarksHandler.js?documentId=${documentId}`, {
      method: 'GET'
    }).then((response) => {
      if (response.status === 200) {
        response.text().then((bookmarksString) => {
          resolve(bookmarksString);
        })
      }
    });
  });
};

```

{% endcode %}
{% endtab %}

{% tab title="bookmarksHandler.js" %}
{% code title="bookmarksHandler.js" lineNumbers="true" %}

```js
const path = require('path');
const fs = require('fs');

module.exports = (app) => {
  // Create xfdf folder if it doesn't exist
  if (!fs.existsSync('server/bookmarks')) {
    fs.mkdirSync('server/bookmarks');
  }

  // Handle POST request sent to '/server/bookmarksHandler.js'
  app.post('/server/bookmarksHandler.js', (request, response) => {
    const bookmarksFile = path.resolve(__dirname, `./bookmarks/${request.query.documentId}.json`);

    try {
      // Write XFDF string into an XFDF file
      response.status(200).send(fs.writeFileSync(bookmarksFile, request.body));
    } catch(e) {
      response.status(500).send(`Error writing bookmarks data to ${bookmarksFile}`);
    }
    response.end();
  });

  // Handle GET request sent to '/server/bookmarksHandler.js'
  app.get('/server/bookmarksHandler.js', (request, response) => {
    const bookmarksFile = path.resolve(__dirname, `./bookmarks/${request.query.documentId}.json`);

    if (fs.existsSync(bookmarksFile)) {
      response.header('Content-Type', 'text/xml');
      // Read from the XFDF file and send the string as a response
      response.status(200).send(fs.readFileSync(bookmarksFile));
    } else {
      response.status(204).send(`${bookmarksFile} is not found.`);
    }
    response.end();
  });
}

```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/web/get-started/samples/webviewer-user-bookmarks-nodejs.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
