Files
zitadel/apps/docs/content/examples/secure-api/pylon.mdx
T
d8ea041c56 docs: introduce versioned docs and migrate to fuma (#11166)
## Todos for release

- [x] Configure Env in docs project on vercel
- [x] Configure Root Path in the docs project on vercel
- [ ] Remove old CSP https://github.com/zitadel/website/pull/1592

## What we did

This pull request migrates the project documentation from the old
`docs/` directory to the new `apps/docs/` directory, introduces a new
documentation system built with Next.js and Fumadocs, and updates all
relevant references, configuration files, and documentation to reflect
this change. It also adds new configuration and ignore files for the new
documentation app, updates CI and linting to exclude the new docs from
certain checks, and revises the contributing guidelines accordingly.

**Documentation System Migration and New Docs App**

* Migrated all documentation from `docs/` to `apps/docs/`, and updated
all references in `README.md`, `CONTRIBUTING.md`, and other files to
point to the new location.
[[1]](diffhunk://#diff-eca12c0a30e25b4b46522ebf89465a03ba72a03f540796c979137931d8f92055L585-L640)
[[2]](diffhunk://#diff-eca12c0a30e25b4b46522ebf89465a03ba72a03f540796c979137931d8f92055L660-R607)
[[3]](diffhunk://#diff-eca12c0a30e25b4b46522ebf89465a03ba72a03f540796c979137931d8f92055L740-R687)
[[4]](diffhunk://#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5L2-R3)
[[5]](diffhunk://#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5L30-R30)
* Added a new Next.js/Fumadocs-based documentation app under
`apps/docs/`, including core app files, layouts, routing, search API,
and a comprehensive `README.md` with development and contribution
instructions.
[[1]](diffhunk://#diff-5a1b07344a2c1b4d3f37b23ff1388b62cd9f57dea3c1cd23d8a0412b7602b132R1-R74)
[[2]](diffhunk://#diff-462b9ad1eabbb7d1c29bb9c36e4931eb180fd7190900e6d2babf8f4d66ad1c28R1-R39)
[[3]](diffhunk://#diff-e16ae25660ded787b10ac35dea96d5ecaacf895dae0afc8a9bd4382dc79a8c87R1-R7)
[apps/docs/app/[[...slug]]/layout.tsxR1-R81](diffhunk://#diff-59e08acde4e805b7aeccef1dcf98f1d71dfc550777e6b9402085cee0e9fa4e0aR1-R81),
[apps/docs/app/[[...slug]]/page.tsxR1-R79](diffhunk://#diff-e5df3f80d0fa01e12d63d81f29c57a9d14e846c78fd3beabb2ef768e38fd9580R1-R79),
[[4]](diffhunk://#diff-389b34918e040cacaa87cd7201ffa462cc2b0b716736f537e3d3c660ac69353bR1-R7)
[[5]](diffhunk://#diff-d3b03416d1c457b19f1c27b26f2db741412df841b875c26ccadc36e4522247f4R1-R29)
[[6]](diffhunk://#diff-c8fb8339570a5305809be7c618e14705fd86390dc278e6ce8ba224a7bc8b0c3cR1-R25)

**Configuration and Tooling Updates**

* Updated `.github/workflows/codeql.yml`, `.golangci.yaml`, and
`.github/dependabot.yml` to properly handle the new docs app: excluded
`apps/docs` from certain checks, added npm dependency updates for the
docs app, and excluded generated content.
[[1]](diffhunk://#diff-12783128521e452af0cfac94b99b8d250413c516ec71fe6d97dbea666ff7ba27L8-R14)
[[2]](diffhunk://#diff-9917ddc9f1c3304218f7269265b746d997c5c0615478177b5fceecd33ef47cb5R5-R6)
[[3]](diffhunk://#diff-9917ddc9f1c3304218f7269265b746d997c5c0615478177b5fceecd33ef47cb5R126-R129)
[[4]](diffhunk://#diff-dd4fbda47e51f1e35defb9275a9cd9c212ecde0b870cba89ddaaae65c5f3cd28R89-R106)
* Updated `.devcontainer/devcontainer.json` to use the latest Go 1.25.3
version for consistency.

**Licensing and Miscellaneous**

* Added `apps/docs/` to the list of licensed directories in
`LICENSING.md`.

These changes ensure the documentation is now maintained in a modern,
scalable system and all project tooling is updated to support the new
structure.

---------

Co-authored-by: Federico Coppede <[email protected]>
2026-01-29 08:38:36 -08:00

307 lines
8.3 KiB
Plaintext

---
title: ZITADEL with Pylon
sidebar_label: Pylon
---
import AppJWT from "../imports/_app_jwt.mdx";
import ServiceuserJWT from "../imports/_serviceuser_jwt.mdx";
import ServiceuserRole from "../imports/_serviceuser_role.mdx";
This integration guide demonstrates the recommended way to incorporate ZITADEL into your [Pylon](https://pylon.cronit.io) service.
It explains how to check the token validity in the API and how to check for permissions.
By the end of this guide, your application will have three different endpoint which are public, private(valid token) and private-scoped(valid token with specific role).
## ZITADEL setup
Before we can start building our application, we have to do a few configuration steps in ZITADEL Management Console.
### Create application
<AppJWT components={props.components} />
### Create Serviceuser
<ServiceuserJWT components={props.components} />
### Give Serviceuser an authorization
<ServiceuserRole components={props.components} />
### Prerequisites
At the end you should have the following for the API:
- Issuer, something like `https://example.zitadel.cloud` or `http://localhost:8080`
- `.json`-key-file for the API, from the application
- ID of the project
And the following from the Serviceuser:
- `.json`-key-file from the serviceuser
## Setup new Pylon service
Pylon allows you to create a new service using the `npm create pylon` command. This command creates a new Pylon project with a basic project structure and configuration.
During the setup process, you can choose your preferred runtime, such as Bun, Node.js, or Cloudflare Workers.
**This guide uses the Bun runtime.**
### Creating a new project
To create a new Pylon project, run the following command:
```bash
npm create pylon my-pylon@latest
```
This will create a new directory called `my-pylon` with a basic Pylon project structure.
### Project structure
Pylon projects are structured as follows:
```
my-pylon/
├── .pylon/
├── src/
│ ├── index.ts
├── package.json
├── tsconfig.json
```
- `.pylon/`: Contains the production build of your project.
- `src/`: Contains the source code of your project.
- `src/index.ts`: The entry point of your Pylon service.
- `package.json`: The npm package configuration file.
- `tsconfig.json`: The TypeScript configuration file.
### Basic example
Here's an example of a basic Pylon service:
```ts
export const graphql = {
Query: {
sum: (a: number, b: number) => a + b,
},
Mutation: {
divide: (a: number, b: number) => a / b,
},
};
export default app;
```
## Secure the API
### Add ZITADEL info to the service
1. Create a `.env` file in the root folder of your project and add the following configuration:
```bash
AUTH_ISSUER='URL to the zitadel instance'
AUTH_PROJECT_ID='ID of the project'
```
It should look something like this:
```bash
AUTH_ISSUER='https://example.zitadel.cloud'
AUTH_PROJECT_ID='250719519163548112'
```
2. Copy the `.json`-key-file that you downloaded from the ZITADEL Management Console into the root folder of your project and rename it to `key.json`.
3. (Optional) For added convenience in production environments, you can include the content of the .json key file as `AUTH_KEY` in the .env file or as an environment variable.
### Auth
Pylon provides a auth module and a decorator to check the validity of the token and the permissions.
- `auth.initialize()`: Initializes the authentication middleware.
- `auth.require()` : Middleware to check if the token is valid.
- `auth.require({roles: ['role']})`: Middleware to check if the token is valid and has the specified roles.
- `requireAuth()`: Decorator to check if the token is valid.
- `requireAuth({roles: ['role']})`: Decorator to check if the token is valid and has the specified roles.
### Build the Pylon service
Now we will create a new Pylon service with the following endpoints:
- `/api/public`: Public endpoint
- `/api/private`: Private endpoint
- `/api/private-scoped`: Private endpoint with specific role
- `/graphql`: GraphQL endpoint
- Query: `me`: Private endpoint that returns the current user and the messages if the role is `read:messages`
- Query: `info`: Public endpoint
### Create the service
The following code demonstrates how to create a Pylon service with the required endpoints, it must be added to the `src/index.ts` file of your project:
```ts
import {
app,
auth,
requireAuth,
getContext,
ServiceError,
} from "@getcronit/pylon";
class User {
id: string;
name: string;
#messages: string[];
constructor(id: string, name: string, messages: string[]) {
this.id = id;
this.name = name;
this.#messages = messages;
}
@requireAuth({ roles: ["read:messages"] })
async messages() {
return this.#messages;
}
static users: User[] = [];
@requireAuth()
static async me() {
const ctx = getContext();
const id = ctx.get("auth")!.sub;
const user = User.users.find((user) => user.id === id);
if (!user) {
throw new ServiceError("User not found", {
statusCode: 404,
code: "USER_NOT_FOUND",
});
}
return user;
}
@requireAuth()
static async create() {
const ctx = getContext();
const auth = ctx.get("auth")!;
// Check if the user already exists
if (User.users.find((user) => user.id === auth.sub)) {
throw new ServiceError("User already exists", {
statusCode: 400,
code: "USER_ALREADY_EXISTS",
});
}
const user = new User(auth.sub, auth.username || "unknown", [
"Welcome to Pylon with ZITADEL!",
]);
User.users.push(user);
return user;
}
}
export const graphql = {
Query: {
me: User.me,
info: () => "Public Data",
},
Mutation: {
createUser: User.create,
},
};
// Initialize the authentication middleware
app.use("*", auth.initialize());
// Automatically try to create a user for each request for demonstration purposes
app.use(async (_, next) => {
try {
await User.create();
} catch {
// Ignore errors
// Fail silently if the user already exists
}
await next();
});
app.get("/img/api/info", (c) => {
return new Response("Public Data");
});
// The `auth.require()` middleware is optional here, as the `User.me` method already checks for it.
app.get("/img/api/me", auth.require(), async (c) => {
const user = await User.me();
return c.json(user);
});
// A role check for `read:messages` is not required here, as the `user.messages` method already checks for it.
app.get("/img/api/me/messages", auth.require(), async (c) => {
const user = await User.me();
// This will throw an error if the user does not have the `read:messages` role
return c.json(await user.messages());
});
export default app;
```
### Call the API
To call the API you need an access token, which is then verified by ZITADEL.
Please follow [this guide here](/guides/integrate/token-introspection/private-key-jwt), ignoring the first step as we already have the `.json`-key-file from the serviceaccount.
<Callout>
You can also create a PAT for the serviceuser and use it to test the API. For this, follow [this guide](/guides/integrate/service-users/personal-access-token#create-a-service-user-with-a-pat).
</Callout>
Optionally set the token as an environment variable:
```
export TOKEN='MtjHodGy4zxKylDOhg6kW90WeEQs2q...'
```
Now you have to start the Pylon service:
```bash
bun run dev
```
With the access token, you can then do the following calls:
1. GraphQL:
```
curl -H "Authorization: Bearer $TOKEN" -G http://localhost:3000/graphql --data-urlencode 'query={ info }'
curl -H "Authorization: Bearer $TOKEN" -G http://localhost:3000/graphql --data-urlencode 'query={ me { id name } }'
curl -H "Authorization: Bearer $TOKEN" -G http://localhost:3000/graphql --data-urlencode 'query={ me { id name messages } }'
```
You can also visit the GraphQL playground at `http://localhost:3000/graphql` and execute the queries there.
2. Routes:
```
curl -H "Authorization: Bearer $TOKEN" -X GET http://localhost:3000/api/info
curl -H "Authorization: Bearer $TOKEN" -X GET http://localhost:3000/api/me
curl -H "Authorization: Bearer $TOKEN" -X GET http://localhost:3000/api/me/messages
```
## Completion
Congratulations! You have successfully integrated your Pylon with ZITADEL!
If you get stuck, consider checking out their [documentation](https://pylon.cronit.io). If you face issues, contact Pylon or raise an issue on [GitHub](https://github.com/getcronit/pylon/issues).