Skip to content
Open

V3 #75

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
141 commits
Select commit Hold shift + click to select a range
4498a08
integrate pylon-builder into pylon-dev and implement pm2 for process …
schettn Feb 18, 2025
a3a7c45
extend plugin system with setup, middleware, and build functions
schettn Feb 18, 2025
fbe2698
add fallback page for landing and unhandled routes; configurable via …
schettn Feb 18, 2025
798f3f4
overhaul authentication system with new useAuth plugin and role-based…
schettn Feb 18, 2025
a305c71
add usePages plugin for file-based routing support in Fullstack React
schettn Feb 18, 2025
a4910f4
improve compatibility
schettn Feb 19, 2025
8ccdce2
add config extraction functionality to bundler
schettn Feb 19, 2025
1a39dd6
add esbuild integration for client bundling in buildClient function
schettn Feb 19, 2025
1865933
create-pylon: enhance logging, simplify flags, and improve error hand…
schettn Feb 19, 2025
acd776d
update lockfile
schettn Feb 19, 2025
6e6f8c0
handle 404 responses in pylon handler and refactor viewer / unhandled…
schettn Feb 19, 2025
e978949
add option to disable the playground and introspection
schettn Feb 19, 2025
802fad5
set default package manager to 'npm' if not specified
schettn Feb 21, 2025
5e23904
ensure NODE_ENV is set to development by default in build configuration
schettn Feb 28, 2025
bb5197b
update moduleResolution to 'bundler' in TypeScript configuration
schettn Feb 28, 2025
496b83c
add precedence attribute to stylesheet link in app file generation
schettn Feb 28, 2025
7a1e285
improve pages build process
schettn Mar 3, 2025
b6e46ba
add PylonImage component for optimized image handling
schettn Mar 3, 2025
73f25c8
add @types/react to devDependencies
schettn Mar 3, 2025
bb96156
update @types/react to version 19.0.10 in pnpm-lock.yaml
schettn Mar 3, 2025
cd079b5
refactor generateAppFile to remove unnecessary Suspense wrapper
schettn Mar 4, 2025
8afe87a
wip: SSR error handling
schettn Mar 4, 2025
9786f6b
set graphiql to true if no option is specified in the config
schettn Mar 5, 2025
a3533ed
Move pages to own package; add error pages and dev overlay
schettn Mar 12, 2025
0d4731c
fix(builder): use property symbol instead of type property (#77)
schettn Mar 12, 2025
6dd8bd7
Merge remote-tracking branch 'origin/main' into v3
schettn Mar 12, 2025
cb863d1
update package dependencies and restructure peer dependencies
schettn Mar 12, 2025
3969e61
remove unused PostCSS plugin integration
schettn Mar 12, 2025
46197dc
replace ts-expect-error with ts-ignore for compatibility
schettn Mar 12, 2025
826d174
add @getcronit/pylon-pages to dependencies and remove peerDependencies
schettn Mar 12, 2025
331210b
move pylon-pages back to pylon
schettn Mar 13, 2025
65029be
move postcss-load-config to dependencies
schettn Mar 13, 2025
6c69119
enhance image handling and optimize performance in image plugin
schettn Mar 13, 2025
914f115
add optional fill prop to Image component for responsive width and he…
schettn Mar 17, 2025
e7fe653
add Link component to pylon pages and export it from index
schettn Mar 17, 2025
f49099a
refactor Image component to improve fill prop handling for responsive…
schettn Mar 17, 2025
c13e536
refactor image caching logic to check cache before downloading images
schettn Mar 17, 2025
2100b1b
add lqip image optimization to pylon image
schettn Mar 17, 2025
0f9128e
add lqip support for generating blurDataURL in usePylonImageValues
schettn Mar 17, 2025
09af0e8
add preload support for blurDataURL in usePylonImageValues
schettn Mar 17, 2025
a23254d
enhance app hydration plugin to support client-side navigation with u…
schettn Mar 18, 2025
4b922ed
refactor app hydration logic to support client-side navigation with u…
schettn Mar 18, 2025
9dbb44a
update build script to include tsc-alias and adjust TypeScript config…
schettn Mar 18, 2025
fb34202
add tsc-alias dependency and update related package versions in pnpm-…
schettn Mar 18, 2025
14679e2
replace fs.readdirSync with glob for improved file retrieval in setup…
schettn Mar 18, 2025
3e410a1
fix publicFiles paths
schettn Mar 18, 2025
cada02b
fix import statement for tiny-glob to include file extension
schettn Mar 18, 2025
d0bb5f0
enhance image path handling to support absolute/relative URLs and imp…
schettn Mar 18, 2025
af032dc
fix image path construction to remove unnecessary directory in setup …
schettn Mar 18, 2025
5fd874f
temporarily disable cache for all requests to prepare for future cach…
schettn Mar 19, 2025
1c22b46
add support for additional font file types in build process
schettn Mar 19, 2025
6b2bdf5
add support for additional font file types in response headers
schettn Mar 19, 2025
125579f
refactor content type handling for font files to default to applicati…
schettn Mar 19, 2025
92455f6
update file handling to support Uint8Array for content comparison and…
schettn Mar 19, 2025
386b61b
update file handling to use Buffer for content comparison and writing
schettn Mar 19, 2025
67abf6b
remove postcssPlugin from the server build process plugins
schettn Mar 25, 2025
6ae5f36
Revert "remove postcssPlugin from the server build process plugins"
schettn Mar 25, 2025
342074b
add mime package and update content type handling for files
schettn Mar 26, 2025
e8eb7b3
set default config value when configCode is not provided
schettn Mar 26, 2025
38fd283
refactor file serving logic into separate serveFilePath function
schettn Mar 26, 2025
14a3753
fix schema building in watch mode
schettn Mar 27, 2025
4746375
remove pylon-telemetry package and update analytics integration
schettn Mar 27, 2025
1aa3d38
execute config before calling the pylon handler
schettn Mar 27, 2025
e2dbba1
remove debug logging for video file serving in serveFilePath function
schettn Mar 27, 2025
7ad3dbe
add rootDir and exclude dist from TypeScript configuration
schettn Mar 28, 2025
40b45e7
add cache busting suffix to bootstrapModules in setup function
schettn Mar 28, 2025
a60dfea
use react-router v7 for data fetching and routing
schettn Apr 7, 2025
56009eb
refactor: simplify app hydration by removing DevOverlay and error han…
schettn Apr 7, 2025
ea8a140
fix hydration for initial route
schettn Apr 7, 2025
1fa4056
add authorization header to client
schettn Apr 8, 2025
565bccf
add authorization header to fetch requests in build-client and app-utils
schettn Apr 8, 2025
a853ef5
pages: enhance loader logic to support internal request handling
schettn Apr 8, 2025
602bf92
enhance image downloading logic to support both absolute URLs and int…
schettn Apr 16, 2025
99c4509
implement multipart form data handling for GraphQL queries in queryFe…
schettn Apr 16, 2025
2bb5eee
enhance plugin configuration and add StatusPage component for improve…
schettn Apr 24, 2025
4a5a7b9
add customizable return link to StatusPage and implement notFound fun…
schettn Apr 24, 2025
cc8b61c
update notFound function to provide a more user-friendly status text
schettn Apr 24, 2025
568e117
remove unused cacheSnapshot preparation in setup function
schettn May 1, 2025
f5bf760
export cache as a constant and clear client cache before preparing Re…
schettn May 1, 2025
f8aab5b
forward client headers for improved server-side handling
schettn May 2, 2025
0abbcf8
fix: prevent bundling of Pylon module by using a variable for import
schettn May 2, 2025
087136d
feat: add forbidden function to handle 403 responses with customizabl…
schettn May 2, 2025
a53a7e9
feat: add unauthorized function to handle 401 responses with customiz…
schettn May 2, 2025
cd7a058
fix: enhance lazy loading to reload window on import failure
schettn May 8, 2025
41f35ab
skip initial build in dev mode
schettn May 13, 2025
8d23bcb
wip: add build start and end logging with consola
schettn May 13, 2025
0c0c003
add rebuild logging plugin to track build duration for pages
schettn May 13, 2025
6556ae0
feat: add style prop to Image component for custom styling
schettn May 21, 2025
16fa11a
Merge branch 'main' into v3
schettn May 21, 2025
a7c6ff0
refactor: remove unused slugs import and clean up whitespace in setup…
schettn May 21, 2025
8f479bd
fix: add initial build steps for app file, public directory, and CSS …
schettn May 21, 2025
0f0ef60
add redirect function and enhance error handling in setup
schettn Jun 10, 2025
56a4809
enhance route component to support props and add loader in layout
schettn Jun 10, 2025
3085eaa
remove log
schettn Jun 10, 2025
65bcb81
feat: add esmExternalsPlugin to handle external ESM dependencies
schettn Jun 10, 2025
750a6b2
add escape-string-regexp dependency to pnpm-lock.yaml
schettn Jun 10, 2025
53944b2
fix: update route component to use props directly in withLoaderData
schettn Jun 10, 2025
a82d94f
fix error handling
schettn Jun 11, 2025
adc01bd
add nested 404 pages and improve pylon style loading
schettn Jun 11, 2025
bffcc61
fix: export LayoutProps
schettn Jul 4, 2025
d158929
add pages context
schettn Jul 4, 2025
281a13c
fix: set platform to 'node' in Bundler context
Aug 12, 2025
5e03ef3
fix: add startTransition to hydrateRoot for improved performance
Aug 20, 2025
d23f2d0
feat: integrate Sentry error handling in hydration process
Aug 20, 2025
7ae273e
wip: seperate client for each layer
Oct 1, 2025
5cde7f2
Merge branch 'main' into v3
Oct 1, 2025
eebcc06
fix: set html header for readable stream rendering
Nov 14, 2025
f652c1f
fix: remove initial scale meta tag
Dec 2, 2025
578c0d2
fix: sanitize dynamic path segments in generated layout component names
Dec 2, 2025
1775cca
feat: add `useRouteData` to expose page props to components
Dec 6, 2025
a59c944
feat: add named route data refetching capabilities via a global regis…
Dec 12, 2025
66ff90c
fix: remove trailing comma from route.Component assignment
Dec 12, 2025
75daf04
refactor: simplify data client hook usage by directly calling `dataCl…
Dec 12, 2025
87ee49d
fix: use `useQuery` and `useHydrateCache` from `dataClient.pageClient…
Dec 15, 2025
8537e3b
fix: use default revalidation arguments for route shouldRevalidate
Dec 15, 2025
a54ebb5
feat(use-pages): implement targeted SSR rendering and snapshot optimi…
Jan 14, 2026
fad8608
fix(use-pages): preserve RootLayout context in targeted SSR rendering
Jan 15, 2026
945f59b
feat(pylon-dev): improve schema generation with structural type dedup…
Jan 27, 2026
94385cb
fix(pylon-dev): handle explicit object, any, and recursive JSON types…
Jan 27, 2026
449e419
fix(pylon-dev): fix typename resolution for anonymous types in generi…
Jan 27, 2026
d7f034e
fix(builder): implement strict structural equality check for input types
Jan 27, 2026
997c55b
feat(builder): implement descriptive naming for implicit argument types
Jan 27, 2026
90e1a31
fix(builder): prevent contextual renaming of scalar input types
Jan 27, 2026
d3ccf30
fix(dev): add JSONObject to client scalars
Jan 28, 2026
c9acf65
fix: favor JSONObject instead of Object
Jan 28, 2026
bfc27ec
feat: implement comprehensive snapshot testing and refine schema gene…
Feb 4, 2026
7d4d52f
fix: refine enum naming and implement empty array fallback
Feb 4, 2026
d71b91c
fix: deduplicate enum and union definitions in GraphQL schema
Feb 4, 2026
5b36416
fix: use static pylon config import to support wrangler
Feb 6, 2026
a2c1ce6
fix: use dynamic pages plugin loading to avoid executing react import…
Feb 6, 2026
53d1f53
fix: config loading
Feb 6, 2026
97fa592
feat(pages): support catch all route
Feb 13, 2026
ec4c54c
feat: implement robust config extraction with dependency tracing
Feb 13, 2026
d86cba7
refactor(pages): route generation and improve catch-all handling
Feb 13, 2026
549fb09
fix: improve dev server speed and stability and add missing onBuild c…
Feb 13, 2026
9a01f9b
chore: add lockfile
Feb 13, 2026
3ee5d58
fix: add missing consola dep
Feb 15, 2026
740c74d
fix: remove debug console log
Feb 15, 2026
c4fb497
fix: add performence improvements
Feb 15, 2026
c84f9f4
fix(pages): ensure client is request-scoped and disable suspense
Feb 15, 2026
695ce41
chore: update lockfile
Feb 15, 2026
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
17 changes: 17 additions & 0 deletions .changeset/gold-boxes-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@getcronit/pylon-dev': major
---

- Integrated `@getcronit/pylon-builder` directly into `@getcronit/pylon-dev`.
- Removed the `pylon-builder` package.
- The builder now utilizes the `esbuild` watch mode for development. This is a much faster and more efficient way to build the project.
- Implemented `pm2` for process management:
- `pm2` is now used to manage the `pylon-dev` server. After files are built, the server is restarted automatically.
- The stdout and stderr logs are logged directly with `consola`.
- Now builds a cross-environment client in `.pylon/client` using `gqty`. This will be used for pylon/pages.

### Breaking Change: Removed Client Generation Feature

- **What**: The client generation feature has been removed.
- **Why**: We have decided to use `gqty` directly to streamline the development process and reduce complexity.
- **How to Update**: Consumers should now use the [GQty CLI](https://gqty.dev/api-reference/cli#basic-usage) directly to generate their clients. Update your build scripts and development workflows to integrate `gqty` as described in the GQty documentation.
40 changes: 40 additions & 0 deletions .changeset/popular-pugs-serve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
'@getcronit/pylon': minor
'@getcronit/pylon-dev': minor
---

Extend plugin system with setup, middleware, and build functions.
The viewer is now integrated via a built-in `useViewer` plugin.

Custom plugins can now access the app instance and register routes, middleware, and custom build steps.

```ts
import {Plugin} from '@getcronit/pylon'

export function myPlugin(): Plugin {
return {
setup(app) {
app.use((req, res, next) => {
console.log('Request:', req.url)
next()
})

app.get('/hello', (req, res) => {
res.send('Hello, World!')
})
},
middleware: (c, next) => {
// This middleware will be inserted higher in the middleware stack
console.log('Middleware:', c.req.url)
next()
},
build: async () => {
// Custom esbuild build
const ctx = await esbuild.context(...)

// Must return the context
return ctx
}
}
}
```
5 changes: 5 additions & 0 deletions .changeset/real-horses-smash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@getcronit/pylon-dev': patch
---

Fix broken field descriptions in schema parsing
26 changes: 26 additions & 0 deletions .changeset/rotten-ravens-sin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
'@getcronit/pylon': minor
---

Add `usePages` plugin to support file-based (Fullstack React) routing. https://github.com/getcronit/pylon/issues/69

```ts
import {app, usePages, PylonConfig} from '@getcronit/pylon'

export const graphql = {
Query: {
hello: () => {
return 'Hello, world!'
},
post: (slug: string) => {
return {title: `Post: ${slug}`, content: 'This is a blog post.'}
}
}
}

export const config: PylonConfig = {
plugins: [usePages()] // Enables the Pages Router
}

export default app
```
13 changes: 13 additions & 0 deletions .changeset/shy-countries-help.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@getcronit/pylon': minor
---

Show a fallback page for the landing page and unhandled routes / 404s.

This behavior can be disabled via the pylon config:

```ts
export const config: PylonConfig = {
landingPage: false
}
```
13 changes: 13 additions & 0 deletions .changeset/slimy-garlics-battle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'create-pylon': patch
---

- Use `consola` for clearer interactive prompts and logs.
- Remove `--client`, `--client-path`, and `--client-port` flags in favor of [GQty CLI](https://gqty.dev/api-reference/cli#basic-usage)
- Improved package manager detection and dependency installation. https://github.com/getcronit/pylon/issues/73
- Removed `--template` flag in favor of `--features` flag. Each runtime can now support multiple features which pre-configure the project for different use-cases.
Currently supported features:
- `pages`: React SSR Pages with file-based routing
- `auth`: OIDC Authentication (Primarily for ZITADEL but can be used with any OIDC provider)
- The success message now only shows the `deploy` script if it is available.
- Improved error handling and messaging.
36 changes: 36 additions & 0 deletions .changeset/soft-goats-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
'@getcronit/pylon': major
---

**Summary:**
This changeset introduces a major overhaul to the built-in authentication system. The new implementation automatically sets up `/auth/login`, `/auth/callback`, and `/auth/logout` routes, injects an `auth` object into the context, and manages token cookies. Role-based route protection is now enhanced via `authMiddleware` and the updated `requireAuth` decorator, configurable through the streamlined `useAuth` plugin.

---

**Breaking Changes:**

- **WHAT:**
The authentication configuration has been completely revamped. The previous manual setup is replaced by the `useAuth` plugin. Custom authentication route definitions are no longer necessary, and existing middleware or decorator usage may require adjustments.

- **WHY:**
This change was implemented to simplify authentication setup, reduce boilerplate, improve security by automating context and cookie management, and offer better role-based access control.

- **HOW:**
Consumers should:
1. Remove any custom authentication route setups.
2. Update their configuration to use the new `useAuth` plugin as shown below:
```typescript
export const config: PylonConfig = {
plugins: [
useAuth({
issuer: 'https://test-0o6zvq.zitadel.cloud',
endpoint: '/auth',
keyPath: 'key.json'
})
]
}
```
3. Replace previous authentication middleware or decorators with the updated `requireAuth` and `authMiddleware` APIs.
4. Test the new authentication endpoints (`/auth/login`, `/auth/callback`, and `/auth/logout`) to ensure proper integration.

Ensure you update your code accordingly to avoid disruptions in your authentication flow.
16 changes: 16 additions & 0 deletions .changeset/young-islands-bow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@getcronit/pylon': minor
---

- Option to disable the playground and introspection in the Pylon configuration. https://github.com/getcronit/pylon/issues/72

### Example

To disable the playground and introspection, set the `graphiql` property to `false` in your Pylon configuration:

```ts
export const config: PylonConfig = {
// Disable the playground and introspection
graphiql: false
}
```
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ node_modules

bun.lockb

.DS_Store
.DS_Store

examples
Original file line number Diff line number Diff line change
Expand Up @@ -2,65 +2,86 @@ import {Callout} from '@components/callout'

# Built-in Authentication and Authorization

Discover how Pylon simplifies user authentication and authorization with its comprehensive built-in features, empowering you to secure your web services effortlessly.
Pylon now offers an enhanced, streamlined authentication system. With this update, the auth endpoint automatically creates routes for **/auth/login**, **/auth/callback**, and **/auth/logout**. When a user authenticates, Pylon sets an `auth` object in the context variables and automatically manages a cookie with the token—simplifying session management and ensuring a secure experience.

---

## General Setup

Before diving into authentication and authorization with Pylon, it's essential to set up your environment and configure the necessary components. Pylon's built-in authentication system follows the OIDC standard and is currently tightly integrated with ZITADEL for user management and access control.
Before you begin, configure your environment to integrate with your authentication provider (e.g., ZITADEL). The new configuration uses the `useAuth` plugin to initialize authentication routes and settings.

1. **Environment Variables:**
Ensure you have the required environment variables set up in your project:
```typescript
import {
app,
PylonConfig,
requireAuth,
useAuth,
authMiddleware
} from '@getcronit/pylon'

export const config: PylonConfig = {
plugins: [
useAuth({
issuer: 'https://test-0o6zvq.zitadel.cloud',
endpoint: '/auth', // optional, default is '/auth'
keyPath: 'key.json' // optional, default is 'key.json'
})
]
}
```

```
AUTH_ISSUER=https://test-0o6zvq.zitadel.cloud
AUTH_PROJECT_ID=<your_auth_project_id>
```
**How it works:**

2. **Integration with ZITADEL:**
To enable Pylon to authenticate users and manage access control, you need to integrate it with ZITADEL. Follow the documentation provided by ZITADEL to set up projects, applications, keys, and roles.
[ZITADEL Projects Documentation](https://zitadel.com/docs/guides/manage/console/projects)
- **Auth Routes:**
The plugin automatically creates routes for:

- `/auth/login`
- `/auth/callback`
- `/auth/logout`

- **Context & Cookie:**
After authentication, an `auth` object is added to your context, and a cookie containing the token is set for subsequent requests.

<Callout type="note" title="Important">
Pylon requires a **API** application with the **Private JWT Key** type to
authenticate users and manage access control.
Ensure that your API application is configured to use a **Private JWT Key**
type for secure token management.
</Callout>

---

## Authentication Example

Pylon makes authentication seamless by providing a straightforward integration with ZITADEL. Here's how you can set up authentication in your Pylon project:
To protect sensitive data, use the `requireAuth` decorator. In the example below, any user trying to access the data must be authenticated:

```typescript
import {app, auth, requireAuth} from '@getcronit/pylon'

// Define your sensitive data service
// Define a service for sensitive data
class SensitiveData {
@requireAuth()
static async getData() {
return 'Sensitive Data'
}
}

// Expose the resolver via GraphQL
export const graphql = {
Query: {
sensitiveData: SensitiveData.getData
}
}

app.use('*', auth.initialize())

export default app
```

In this example, the `requireAuth()` decorator ensures that users are authenticated before accessing sensitive data. You can also specify roles to restrict access to certain data based on user permissions.
In this setup, the `@requireAuth()` decorator ensures that only authenticated users can access the `getData` method. If the user is not authenticated, they will be redirected to the login flow at `/auth/login`.

---

## Authorization Example

Authorization in Pylon allows you to control access to specific resources based on user roles and permissions. Here's how you can implement authorization in your Pylon project:
If you need to restrict access based on roles, you can pass a roles array to the `requireAuth` decorator. For instance, the following example limits access to users with the `"admin"` role:

```typescript
// Define your sensitive data service
// Define a service for admin-only data
class SensitiveData {
@requireAuth({
roles: ['admin']
Expand All @@ -70,72 +91,63 @@ class SensitiveData {
}
}

// Define your GraphQL schema
// Expose the resolver via GraphQL
export const graphql = {
Query: {
sensitiveAdminData: SensitiveData.getAdminData
}
}

app.use('*', auth.initialize())

export default app
```

In this example, the `requireAuth()` decorator ensures that only authenticated users with the "admin" role can access the `getAdminData()` function. You can customize roles and permissions according to your application's requirements.
Only authenticated users who have the `"admin"` role will be allowed to access `getAdminData()`. Roles should be managed in your authentication provider (e.g., ZITADEL) for centralized control over permissions.

Roles can be defined in ZITADEL and assigned to users to control access to specific resources. By integrating Pylon with ZITADEL, you can easily manage roles and permissions for your application.
For more information on setting up roles in ZITADEL, refer to the [ZITADEL Roles Documentation](https://zitadel.com/docs/guides/manage/console/roles).
---

## Securing Routes
## Securing Routes with Middleware

Securing routes in Pylon involves enforcing authentication and, optionally, authorization for specific endpoints or routes. Here's how you can secure a route in your Pylon project:
In addition to securing individual resolvers, you can enforce authentication and authorization for entire routes using the new `authMiddleware`. For example, to secure a specific REST endpoint:

```typescript
import {auth, requireAuth} from '@getcronit/pylon'

// Define your sensitive data service
class SensitiveData {
static async getData() {
return 'Sensitive Data'
}
import {authMiddleware} from '@getcronit/pylon'

@requireAuth({
// Secure all routes under /admin to only allow users with the 'admin' role
app.use(
'/admin',
authMiddleware({
roles: ['admin']
})
static async getAdminData() {
return 'Admin Data'
}
}
)

export const graphql = {
Query: {
sensitiveData: SensitiveData.getData,
sensitiveAdminData: SensitiveData.getAdminData
// Secure specific route to only allow users with the 'admin' role
app.get(
'/secure',
authMiddleware({
roles: ['admin']
}),
c => {
return c.json({data: 'sensitive'})
}
}

// Enforce authentication for all routes
app.use('*', auth.initialize())

// Secure a specific route with authentication and authorization
app.use('/admin', auth.requireAuth({roles: ['admin']}))

)
export default app
```

In this example, we're securing the `/admin` route to ensure that only authenticated users with the "admin" role can access it. By using the `requireAuth()` middleware from Pylon's authentication module, we enforce both authentication and authorization for this specific route.
In this case, any request to the `/admin` route will first pass through `authMiddleware`, ensuring that the user is authenticated and has the required `"admin"` role.
The same applies to the `/secure` route, which is secured with the `authMiddleware` middleware.

You can customize the route and the required roles according to your application's requirements. This ensures that sensitive endpoints are protected, providing a secure environment for your users' data and resources.
---

## Further Resources

For detailed instructions on setting up projects, applications, keys, and roles in ZITADEL, refer to the ZITADEL documentation:
For additional guidance on integrating with your authentication provider, please refer to the following resources:

- [ZITADEL Projects Documentation](https://zitadel.com/docs/guides/manage/console/projects)
- [ZITADEL Applications Documentation](https://zitadel.com/docs/guides/manage/console/applications#api)
- [ZITADEL Roles Documentation](https://zitadel.com/docs/guides/manage/console/roles)

---

## Conclusion

With Pylon's built-in authentication and authorization features, you can easily secure your web services and control access to sensitive data, providing a seamless and secure user experience.
With the new built-in authentication and authorization features, Pylon makes securing your web services simpler than ever. The automatic route creation, context management, and cookie handling streamline the login flow, while decorators and middleware give you granular control over access to your application’s data and routes. Enjoy a secure and seamless user experience with minimal configuration!
Loading