# Add PDF functionality with React + Vite

Nutrient Web SDK is a JavaScript PDF library for viewing, annotating, and editing PDFs directly in the browser. Use it to add PDF capabilities to any web app.

This guide walks you through the steps to integrate Nutrient Web SDK into your project. By the end, you’ll be able to render a PDF document in the user interface (UI).

**Test without installing**

You can test the SDK capabilities in our playground.

[Read more](https://nutrient.io/demo/sandbox)

**View example**

Prefer to jump straight into code? View the example repo on GitHub.

[Read more](https://github.com/PSPDFKit/nutrient-examples/tree/main/examples/react)

## Installation

You can load Nutrient Web SDK directly from Nutrient’s content delivery network (CDN). Nutrient maintains the CDN for customers, and it’s our recommended way to get started. For more control and flexibility, use the local installation option.

#### Note: Creating a new project (optional)

If you don’t yet have a React project set up, create one with Vite’s React template.

**Steps:**

1. Run the following command to create a new Vite project:

   ```bash

   npm create vite nutrient-react-example --template react
   # or

   yarn create vite nutrient-react-example --template react
   # or

   pnpm create vite nutrient-react-example --template react
   ```

2. Navigate to the project directory:

   ```sh

   cd nutrient-react-example
   ```

3. Install dependencies (skip this if they were already installed during project creation):

### CDN installation

**Steps:**

1. Add the following `<script>` tag in your `index.html` file:

   ```html <!-- Lines inserted: [12] -->

   // index.html
   <!doctype html>
   <html lang="en">
     <head>
       <meta charset="UTF-8" />
       <link rel="icon" type="image/svg+xml" href="/vite.svg" />
       <meta name="viewport" content="width=device-width, initial-scale=1.0" />
       <title>Vite + React + TS</title>
     </head>
     <body>
       <div id="root"></div>
       <script src="https://cdn.cloud.nutrient.io/pspdfkit-web@1.14.0/nutrient-viewer.js"></script>
       <script type="module" src="/src/main.tsx"></script>
     </body>
   </html>
   ```

2. You’re now ready to use Nutrient Web SDK and reference `window.NutrientViewer` in the client-side code.

### Install via package manager

**Steps:**

1. Add the Nutrient Web SDK (`@nutrient-sdk/viewer`) dependency:

   ```bash

   npm install @nutrient-sdk/viewer
   # or

   yarn add @nutrient-sdk/viewer
   # or

   pnpm install @nutrient-sdk/viewer
   ```

2. If you tried CDN installation first, make sure to remove the script tag:

   ```html <!-- Lines deleted: [2] -->

   // index.html
   <script src="https://cdn.cloud.nutrient.io/pspdfkit-web@1.14.0/nutrient-viewer.js"></script>
   <script type="module" src="/src/main.tsx"></script>
   ```

3. You’re now ready to use Nutrient Web SDK locally in your React + Vite app.

## CSS setup requirements

> Nutrient Web SDK requires that the mounting container has an explicit width and height before calling `NutrientViewer.load()`. The container cannot be `0×0` pixels or the SDK will fail to initialize.

**Steps:**

1. For new Vite projects — Remove conflicting CSS from your `src/index.css` file. The default Vite React template includes CSS that interferes with container dimensions:

   ```css <!-- Lines deleted: [2, 3] -->

   /* src/index.css - Remove these properties from body */
   display: flex;
   place-items: center;
   ```

2. Ensure your viewer container has explicit dimensions. The React examples in this guide use inline styles (`style={{ height: "100vh", width: "100vw" }}`), which is the recommended approach for most projects.

3. For existing projects — Check for any CSS framework styles that might interfere with container positioning or dimensions, and override them as needed.

## Rendering a PDF

### CDN installation

**Steps:**

1. Load the PDF file in `App.tsx`, as shown below:

   ```tsx <!-- Lines inserted: [{range: "5-22"}, 24, 26] -->

   // App.tsx
   import { useEffect, useRef } from "react";

   function App() {
     const containerRef = useRef(null);

     useEffect(() => {
       const container = containerRef.current;

       const { NutrientViewer } = window;
       if (container && NutrientViewer) {
         NutrientViewer.load({
           container,
           // You can also specify a file in public directory, for example `/nutrient-web-demo.pdf`.
           document: "https://www.nutrient.io/downloads/nutrient-web-demo.pdf",
         });
       }

       return () => {
         NutrientViewer?.unload(container);
       };
     }, []);

     // Set the container height and width.
     return (
       // Make sure to set the container height and width explicitly.
       <div ref={containerRef} style={{ height: "100vh", width: "100vw" }} />
     );
   }

   export default App;
   ```

2. Start the development server:

   ```bash

   npm run dev
   # or

   yarn dev
   # or

   pnpm dev
   ```

   > In development, React 18+ runs `useEffect` twice to help detect issues with cleanup functions if you’re using `StrictMode`. This may cause a brief “double mounting” warning in the console. The cleanup function (`NutrientViewer.unload`) in the code above handles this correctly. This behavior only occurs in development mode and won’t affect production builds.

3. You’ll see the PDF rendered in the Nutrient Web SDK user interface (UI).

### Install via package manager

**Steps:**

1. With package manager installation, access the Nutrient Web SDK module directly. Update your `App.tsx` file to load the PDF file as shown below:

   ```tsx <!-- Lines inserted: [{range: "5-31"}, {range: "36-37"}] -->

   // App.tsx
   import { useEffect, useRef } from "react";

   function App() {
     const containerRef = useRef(null);

     useEffect(() => {
       const container = containerRef.current;
       let cleanup = () => {};

       (async () => {
         const NutrientViewer = (await import("@nutrient-sdk/viewer")).default;

         // Ensure there’s only one `NutrientViewer` instance.
         NutrientViewer.unload(container);

         if (container && NutrientViewer) {
           NutrientViewer.load({
             container,
             // You can also specify a file in public directory, for example /nutrient-web-demo.pdf.
             useCDN: true,
             document:
               "https://www.nutrient.io/downloads/nutrient-web-demo.pdf",
           });
         }

         cleanup = () => {
           NutrientViewer.unload(container);
         };
       })();

       return cleanup;
     }, []);

     // Set the container height and width.
     return (
       // Make sure to set the container height and width explicitly.
       <div ref={containerRef} style={{ height: "100vh", width: "100vw" }} />
     );
   }

   export default App;
   ```

   > **Note:** Adding `useCDN: true` will load the SDK assets from the CDN if `baseUrl` isn’t provided. This flag was introduced in version 1.9.0. If your setup relies on the previous behavior of autodetecting the assets without `baseUrl`, you can omit this flag for now, but be aware that this behavior is deprecated. In future versions, loading from CDN will become a default when `baseUrl` isn’t explicitly provided. `useCDN: true` has no effect if `baseUrl` is set.

   **Optional**: If you decide to self-host the Nutrient Web SDK assets as [described in this guide](https://www.nutrient.io/guides/web/self-host-assets.md), make sure to provide a `baseUrl` in your configuration, as shown below:

   ```tsx

   NutrientViewer.load({
     container,
     useCDN: true,
     document: "https://www.nutrient.io/downloads/nutrient-web-demo.pdf",
     baseUrl: `${window.location.protocol}//${window.location.host}/${
       import.meta.env.PUBLIC_URL?? "" // Usually empty for Vite, but supports custom deployments.
     }`,
   });
   ```

2. Start the development server:

   ```bash

   npm run dev
   # or

   yarn dev
   # or

   pnpm dev
   ```

   > In development, React 18+ runs `useEffect` twice to help detect issues with cleanup functions if you’re using `StrictMode`. This may cause a brief “double mounting” warning in the console. The code above handles this by calling `NutrientViewer.unload(container)` before loading a new instance. This behavior only occurs in development mode and won’t affect production builds.

## Next steps

This section outlines additional steps for setting up your project.

### TypeScript with CDN installation

Nutrient Web SDK comes with built-in support for TypeScript. This should work out of the box for the package manager installation. For the CDN installation, follow steps below.

**Steps:**

1. Add the Nutrient Web SDK dependency, if not done previously. You need the package installed locally to reference the types:

   ```bash

   npm install @nutrient-sdk/viewer
   # or

   yarn add @nutrient-sdk/viewer
   # or

   pnpm install @nutrient-sdk/viewer
   ```

2. Create a module for custom typings — for example, `global.d.ts` in the `src` directory — to reference the built-in typings for the SDK:

   ```ts

   // src/global.d.ts
   import NutrientViewer from "@nutrient-sdk/viewer";

   declare global {
     interface Window {
       // Nutrient Web SDK will be available on `window.NutrientViewer` once loaded.
       NutrientViewer?: typeof NutrientViewer;
     }
   }
   ```

3. Restart the TypeScript server or your editor, if needed.

### Optimizing the CDN installation

If you use the CDN installation approach in production, we recommend considering optimizations such as [prefetching](https://developer.mozilla.org/en-US/docs/Glossary/Prefetch).

### Optimizing load performance

If your app doesn't open a PDF immediately — for example, the user navigates to a viewer on a different page — call [`NutrientViewer.preloadWorker()`](https://www.nutrient.io/api/web/functions/NutrientViewer.preloadWorker.html) early in your app to fetch and compile the WebAssembly artifacts in the background. When `NutrientViewer.load()` runs later, it can start rendering without waiting for them.

```js

// Call early — for example, on app init or after login.
NutrientViewer.preloadWorker();

```

Refer to the [performance best practices](https://www.nutrient.io/guides/web/best-practices/performance.md) guide for more optimization techniques.




## Troubleshooting

If you encounter issues, refer to the [common issues](https://www.nutrient.io/guides/web/troubleshooting/common-issues.md) guide.

> **Note for developers using AI coding assistants**: To get accurate troubleshooting help, copy the content from the [troubleshooting](https://www.nutrient.io/guides/web/troubleshooting/common-issues.md) guide, and include it in your prompt, along with your specific error.

**Test without installing**

You can test the SDK capabilities in our playground.

[Read more](https://nutrient.io/demo/sandbox)

**View example**

Prefer to jump straight into code? View the example repo on GitHub.

[Read more](https://github.com/PSPDFKit/nutrient-examples/tree/main/examples/react)
---

## Related pages

- [Get started with Web SDK](/sdk/web/getting-started.md)
- [Add PDF functionality with TypeScript](/sdk/web/getting-started/typescript.md)
- [Add PDF functionality with Next.js](/sdk/web/getting-started/nextjs.md)

