Skip to content
136 changes: 81 additions & 55 deletions tutorials/client/sdks/web/next-js.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
---

## Introduction
In this tutorial, well explore how to enhance a Next.js application with offline-first capabilities using PowerSync. In the following sections, well walk through the process of integrating PowerSync into a Next.js application, setting up local-first storage, and handling synchronization efficiently.
In this tutorial, we'll explore how to enhance a Next.js application with offline-first capabilities using PowerSync. In the following sections, we'll walk through the process of integrating PowerSync into a Next.js application, setting up local-first storage, and handling synchronization efficiently.

<Note>At present PowerSync will not work with SSR enabled with Next.js and in this guide we disable SSR across the entire app. However, it is possible to have other pages, which do not require authentication for example, to still be rendered server-side. This can be done by only using the DynamicSystemProvider (covered further down in the guide) for specific pages. This means you can still have full SSR on other page which do not require PowerSync.</Note>
<Note>
PowerSync is tailored for client-side applications — there isn't much benefit to using SSR with PowerSync. Some frameworks like Next.js push towards enabling SSR by default, which means code is evaluated in a Node.js runtime. The PowerSync Web SDK requires browser APIs which are not available in Node.js. For ergonomics, the SDK performs no-ops if used in Node.js (rather than throwing errors), but you should not expect any data from PowerSync during server-side rendering. If you are using SSR in your application, we recommend explicitly isolating PowerSync to client-side code.
</Note>

## Setup

Expand Down Expand Up @@ -36,15 +38,13 @@
Would you like to use Tailwind CSS? Yes
Would you like your code inside a `src/` directory? Yes
Would you like to use App Router? (recommended) Yes
Would you like to use Turbopack for `next dev`? No
Would you like to use Turbopack for `next dev`? Yes
Would you like to customize the import alias (`@/*` by default)? Yes
```

<Warning>
Do not use Turbopack when setting up a new Next.js project as we’ll be updating the `next.config.ts` to use Webpack. This is done because we need to enable:
1. asyncWebAssembly
2. topLevelWait
</Warning>
<Info>
Turbopack is supported in Next.js 16+. If you're using an older version of Next.js, see the [Webpack configuration (legacy)](#webpack-configuration-legacy) section below.

Check warning on line 46 in tutorials/client/sdks/web/next-js.mdx

View check run for this annotation

Mintlify / Mintlify Validation (powersync) - vale-spellcheck

tutorials/client/sdks/web/next-js.mdx#L46

Did you really mean 'Turbopack'?
</Info>

### Install PowerSync Dependencies

Expand All @@ -70,27 +70,72 @@

<Note>This SDK currently requires [@journeyapps/wa-sqlite](https://www.npmjs.com/package/@journeyapps/wa-sqlite) as a peer dependency.</Note>

### Copy Worker Assets

When using Turbopack, you need to copy the PowerSync worker files to your public directory. Add a `postinstall` script to your `package.json`:

Check warning on line 75 in tutorials/client/sdks/web/next-js.mdx

View check run for this annotation

Mintlify / Mintlify Validation (powersync) - vale-spellcheck

tutorials/client/sdks/web/next-js.mdx#L75

Did you really mean 'Turbopack'?

```json package.json
{
"scripts": {
"postinstall": "powersync-web copy-assets -o public"

Check warning on line 80 in tutorials/client/sdks/web/next-js.mdx

View check run for this annotation

Mintlify / Mintlify Validation (powersync) - vale-spellcheck

tutorials/client/sdks/web/next-js.mdx#L80

Did you really mean 'postinstall'?
}
}
```

Then run the script to copy the assets:

<CodeGroup>

```shell npm
npm run postinstall
```

```shell yarn
yarn postinstall
```

```shell pnpm
pnpm postinstall
```

</CodeGroup>

This copies the pre-bundled worker files to `public/@powersync/`, which are required since Turbopack doesn't support dynamic imports of workers yet.

Check warning on line 103 in tutorials/client/sdks/web/next-js.mdx

View check run for this annotation

Mintlify / Mintlify Validation (powersync) - vale-spellcheck

tutorials/client/sdks/web/next-js.mdx#L103

Did you really mean 'Turbopack'?

<Note>Add `public/@powersync/*` to your `.gitignore` file since these are generated assets.</Note>

## Next.js Config Setup

In order for PowerSync to work with the Next.js we'll need to modify the default `next.config.ts` to support PowerSync.
For Next.js 16+ with Turbopack, the configuration is minimal:

Check warning on line 109 in tutorials/client/sdks/web/next-js.mdx

View check run for this annotation

Mintlify / Mintlify Validation (powersync) - vale-spellcheck

tutorials/client/sdks/web/next-js.mdx#L109

Did you really mean 'Turbopack'?

```typescript next.config.ts
module.exports = {
experimental: {
turbo: false,
},
webpack: (config: any, isServer: any) => {
images: {
disableStaticImages: true
},
turbopack: {}
};
```

Run `pnpm dev` to start the development server and check that everything compiles correctly, before moving onto the next section.

### Webpack configuration (legacy)

If you're using an older version of Next.js (before 16) or prefer to use Webpack, use this configuration instead:

```typescript next.config.ts
module.exports = {
webpack: (config: any, { isServer }: any) => {
config.experiments = {
...config.experiments,
asyncWebAssembly: true, // Enable WebAssembly in Webpack
asyncWebAssembly: true,
topLevelAwait: true,
};

// For Web Workers, ensure proper file handling
if (!isServer) {
config.module.rules.push({
test: /\.wasm$/,
type: "asset/resource", // Adds WebAssembly files to the static assets
type: "asset/resource",
});
}

Expand All @@ -99,11 +144,6 @@
}
```

Some important notes here, we have to enable `asyncWebAssemply` in Webpack, `topLevelAwait` is required and for Web Workers, ensure proper file handling.
It's also important to add web assembly files to static assets for the site. We will not be using SSR because PowerSync does not support it.

Run `pnpm dev` to start the development server and check that everything compiles correctly, before moving onto the next section.

## Configure a PowerSync Instance
Now that we've got our project setup, let's create a new PowerSync Cloud instance and connect our client to it.
For the purposes of this demo, we'll be using Supabase as the source backend database that PowerSync will connect to.
Expand Down Expand Up @@ -235,33 +275,36 @@
import { AppSchema } from '@/lib/powersync/AppSchema';
import { BackendConnector } from '@/lib/powersync/BackendConnector';
import { PowerSyncContext } from '@powersync/react';
import { PowerSyncDatabase, WASQLiteOpenFactory, WASQLiteVFS, createBaseLogger, LogLevel } from '@powersync/web';
import { PowerSyncDatabase, WASQLiteOpenFactory, createBaseLogger, LogLevel } from '@powersync/web';
import React, { Suspense } from 'react';

const logger = createBaseLogger();
logger.useDefaults();
logger.setLevel(LogLevel.DEBUG);

const factory = new WASQLiteOpenFactory({
dbFilename: 'powersync.db',
// Use the pre-bundled worker from public/@powersync/
// This is required since Turbopack doesn't support dynamic imports of workers yet
worker: '/@powersync/worker/WASQLiteDB.umd.js'
});

export const db = new PowerSyncDatabase({
database: factory,
schema: AppSchema,
database: new WASQLiteOpenFactory({
dbFilename: 'exampleVFS.db',
vfs: WASQLiteVFS.OPFSCoopSyncVFS,
flags: {
enableMultiTabs: typeof SharedWorker !== 'undefined',
ssrMode: false
}
}),
flags: {
enableMultiTabs: typeof SharedWorker !== 'undefined',
disableSSRWarning: true
},
sync: {
// Use the pre-bundled sync worker from public/@powersync/
worker: '/@powersync/worker/SharedSyncImplementation.umd.js'
}
});

const connector = new BackendConnector();
db.connect(connector);

export const SystemProvider = ({ children }: { children: React.ReactNode }) => {

return (
<Suspense>
<PowerSyncContext.Provider value={db}>{children}</PowerSyncContext.Provider>
Expand All @@ -270,38 +313,22 @@
};

export default SystemProvider;

```

The `SystemProvider` will be responsible for initializing the `PowerSyncDatabase`. Here we supply a few arguments, such as the AppSchema we defined earlier along with very important properties such as `ssrMode: false`.
PowerSync will not work when rendered server side, so we need to explicitly disable SSR.
The `SystemProvider` is responsible for initializing the `PowerSyncDatabase`. The worker paths point to the pre-bundled workers copied to the public directory by the `powersync-web copy-assets` command.

We also instantiate our `BackendConnector` and pass an instance of that to `db.connect()`. This will connect to the PowerSync instance, validate the token supplied in the `fetchCredentials` function and then start syncing with the PowerSync service.

#### DynamicSystemProvider.tsx

Add a new file in the newly created `providers` directory called `DynamicSystemProvider.tsx`.

```typescript components/providers/DynamicSystemProvider.tsx
'use client';

import dynamic from 'next/dynamic';

export const DynamicSystemProvider = dynamic(() => import('./SystemProvider'), {
ssr: false
});

```
We can only use PowerSync in client side rendering, so here we're setting `ssr:false`

#### Update `layout.tsx`

In our main `layout.tsx` we'll update the `RootLayout` function to use the `DynamicSystemProvider` created in the last step.
In our main `layout.tsx` we'll update the `RootLayout` function to use the `SystemProvider`.

```typescript app/layout.tsx
'use client';

import { SystemProvider } from '@/app/components/providers/SystemProvider';
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { DynamicSystemProvider } from '@/app/components/providers/DynamicSystemProvider';

const geistSans = Geist({
variable: "--font-geist-sans",
Expand All @@ -322,12 +349,11 @@
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
<DynamicSystemProvider>{children}</DynamicSystemProvider>
<SystemProvider>{children}</SystemProvider>
</body>
</html>
);
}

```

#### Use PowerSync
Expand Down