Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# PowerSync Write API Demo

![Architecture diagram](./diagram.png)

## Project Layout

```
write-api/
├── docker-compose.yaml # Postgres + MongoDB + PowerSync
├── config/
│ ├── powersync.yaml # PowerSync service config
│ └── sync_rules.yaml # Sync rules (lists + todos)
├── init-scripts/
│ └── setup.sql # DB schema + seed data
├── powersync-nodejs-backend-todolist-demo/ # Backend (Express, port 6060)
│ └── .env
└── demo-app/ # Frontend (React/Vite, port 5173)
└── .env.local
```

## Running Everything

```bash
# 1. Start infrastructure (Postgres, Mongo, PowerSync)
docker compose up -d

# 2. Start backend (new terminal)
cd backend && pnpm install && pnpm start

# 3. Start frontend (new terminal)
cd frontend && pnpm install && pnpm dev
```

- Frontend: http://localhost:5173
- Backend: http://localhost:6060
- PowerSync: http://localhost:8080
- Postgres: localhost:5432

## Generating Types from OpenAPI Spec

Both the backend and frontend generate TypeScript types from the shared `openapi.yaml` spec.

```bash
# Backend (generates src/generated/api.ts)
cd backend && pnpm generate-types

# Frontend (generates src/generated/api.d.ts)
cd frontend && pnpm generate
```
8 changes: 8 additions & 0 deletions backend/.env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
POWERSYNC_PRIVATE_KEY=
POWERSYNC_PUBLIC_KEY=
POWERSYNC_URL=
PORT=
JWT_ISSUER=
# Either 'mongodb', 'mysql', 'mssql' or 'postgres'. This defaults to Postgres
DATABASE_TYPE=
DATABASE_URI=
3 changes: 3 additions & 0 deletions backend/.envrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
layout node
use node
[ -f .env ] && dotenv
6 changes: 6 additions & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules
.env
.idea
error.log
combined.log
*.tsbuildinfo
1 change: 1 addition & 0 deletions backend/.nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v20.9.0
2 changes: 2 additions & 0 deletions backend/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Ignore all node_modules
**/node_modules/**
8 changes: 8 additions & 0 deletions backend/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"useTabs": false,
"printWidth": 120,
"trailingComma": "none"
}
30 changes: 30 additions & 0 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Use Node.js 20 Docker image as base
FROM node:20

ENV DATABASE_URI=
# Either 'mongodb', 'postgres', 'mssql' or 'mysql'. This defaults to Postgres
ENV DATABASE_TYPE=
ENV POWERSYNC_PRIVATE_KEY=
ENV POWERSYNC_PUBLIC_KEY=
ENV POWERSYNC_URL=
ENV PORT=
ENV JWT_ISSUER=

# Set the working directory inside the container

RUN npm install -g pnpm@9

WORKDIR /app

# Copy the package.json and package-lock.json files to the container
COPY package*.json ./
COPY pnpm-lock*.yaml ./

# Install dependencies
RUN pnpm install --frozen-lockfile

# Copy the rest of the demo launcher code to the container
COPY / ./

# Command to run the application
CMD ["pnpm", "start"]
121 changes: 121 additions & 0 deletions backend/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
Creative Commons Legal Code

CC0 1.0 Universal

CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.

Statement of Purpose

The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").

Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.

For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.

1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:

i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.

2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.

3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.

4. Limitations and Disclaimers.

a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.
115 changes: 115 additions & 0 deletions backend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# Backend

## Overview

Node.js server application with HTTP endpoints to authorize a [PowerSync](https://www.powersync.com/) enabled application to sync data between a client device and a PostgreSQL, MySQL, MSSQL or MongoDB database.

The endpoints are as follows:

1. GET `/api/auth/token`

- Returns a JWT access token used for PowerSync authentication.
- Provide an optional `user_id` query parameter to set the subject of the JWT.

2. GET `/api/auth/keys`

- JWKS endpoint used by the PowerSync service to validate JWTs.

3. POST `/api/data`

- Accepts a batch of CRUD operations (PUT/PATCH/DELETE) from the client.

4. PUT `/api/data/checkpoint`

- Returns a custom write checkpoint for a given user/client.

## Packages

[node-postgres](https://github.com/brianc/node-postgres) is used to interact with the Postgres database when a client performs requests to the `/api/data` endpoint.

[mongodb](https://www.npmjs.com/package/mongodb) is used to interact with the MongoDB database when a client performs requests to the `/api/data` endpoint.

[mysql2](https://www.npmjs.com/package/mysql2) is used to interact with the MySQL database when a client performs requests to the `/api/data` endpoint.

[node-mssql](https://www.npmjs.com/package/mssql) is used to connect to a MSSQL database to perform operations from the `/api/data` endpoint.

[jose](https://github.com/panva/jose) is used to sign the JWT which PowerSync uses for authorization.

## Requirements

Based on configuration, this app needs a Postgres, Mongo, MSSQL or MySQL instance. Easiest is probably to use docker containers for these databases.
Hosted free versions that can also be used:

1. Postgres: For a free version for testing/demo purposes, visit [Supabase](https://supabase.com/).

## Running the app

1. Clone the repository
2. Follow the steps outlined in [PowerSync Custom Authentication Example](https://github.com/journeyapps/powersync-jwks-example) → [Generate a key-pair](https://github.com/journeyapps/powersync-jwks-example#1-generate-a-key-pair) to get the keys you need for this app. This is an easy way to get started with this demo app. You can use your own public/private keys as well. Note: This backend will generate a temporary key pair for development purposes if the keys are not present in the `.env` file. This should not be used in production.
3. Create a new `.env` file in the root project directory and add the variables as defined in the `.env` file:

```shell
cp .env.template .env
```

4. Install dependancies

```shell
nvm use
```

```shell
pnpm install
```

## Start App

1. Run the following to start the application

```shell
pnpm start
```

This will start the app on `http://127.0.0.1:PORT`, where PORT is what you specify in your `.env` file.

2. Test if the app is working by opening `http://127.0.0.1:PORT/api/auth/token/` in the browser

3. You should get a JSON object as the response to that request

## Connecting the app with PowerSync

This process is only designed for demo/testing purposes, and is not intended for production use. You won't be using ngrok to host your application and database.

1. Download and install [ngrok](https://ngrok.com/)
2. Run the ngrok command to create a HTTPS tunnel to your local application

```shell
ngrok http 8000
```

This should create the tunnel and a new HTTPS URL should be availible e.g.

```shell
ngrok by @inconshreveable (Ctrl+C to quit)

Session Status online
Account Michael Barnes (Plan: Free)
Update update available (version 2.3.41, Ctrl-U to update)
Version 2.3.40
Region United States (us)
Web Interface http://127.0.0.1:4040
Forwarding http://your_id.ngrok-free.app -> http://localhost:8000
Forwarding https://your_id.ngrok-free.app -> http://localhost:8000

Connections ttl opn rt1 rt5 p50 p90
1957 0 0.04 0.03 0.01 89.93
```

3. Open the [PowerSync Dashboard](https://powersync.journeyapps.com/) and paste the `Forwarding` URL starting with HTTPS into the Credentials tab of your PowerSync instance e.g.

```
JWKS URI
https://your_id.ngrok-free.app/api/auth/keys/
```

Pay special attention to the URL, it should include the `/api/auth/keys/` path as this is used by the PowerSync server to validate tokens.
Loading