Skip to main content
Account
Lesson 7 of 9

Integrating with an Astro Application

Learn how to integrate Zitadel with an Astro application, configure authentication, and manage user sessions. We'll cover the PKCE flow, token introspection, and adding user roles.

Integrating with an Astro Application

Building on Previous Knowledge

In the previous video, we set up a basic application that could authenticate with Zitadel and visualize the JWT. Now we’re taking it a step further by integrating Zitadel into a real web application using Astro.

What We’ll Build

In this tutorial, we’ll:

  • Set up an Astro application with server-side rendering
  • Configure Zitadel OAuth with PKCE flow
  • Implement login and callback endpoints
  • Handle JWT tokens and user sessions
  • Display user information after authentication

Prerequisites

Before starting, make sure you have:

  • An Astro application (created with bun create astro@latest)
  • A Zitadel instance (Cloud or self-hosted)
  • Basic understanding of OAuth 2.0 and PKCE

Setting Up Dependencies

Install Arctic for OAuth helpers, the JWT decoder used below, and the ID-token claim types:

Terminal window
bun add arctic @oslojs/jwt
bun add -d oidc-client-ts

Arctic handles all the heavy lifting for OAuth and OIDC flows, making our integration straightforward.

Environment Configuration

Create an .envrc file (or .env if you prefer) with your Zitadel configuration:

Terminal window
export ZITADEL_CLIENT_ID="your-client-id"
export ZITADEL_URL="https://your-instance.zitadel.cloud"

Configuring Astro

Update your astro.config.mjs to enable server-side rendering and configure environment variables:

import { defineConfig } from 'astro/config';
export default defineConfig({
output: 'server',
env: {
schema: {
ZITADEL_URL: {
type: 'string',
context: 'server',
access: 'public',
},
ZITADEL_CLIENT_ID: {
type: 'string',
context: 'server',
access: 'public',
},
},
validateSecrets: true,
},
});

Creating the Zitadel Integration

Create a lib/zitadel.ts file to handle the OAuth flow:

import { ZITADEL_URL, ZITADEL_CLIENT_ID } from 'astro:env/server';
import { generateCodeChallenge, generateState } from 'arctic';
import { decodeJWT } from '@oslojs/jwt';
import type { IdTokenClaims } from 'oidc-client-ts';
export class Zitadel {
private authorizationEndpoint: string;
private tokenEndpoint: string;
private redirectURI: string;
constructor() {
this.authorizationEndpoint = `${ZITADEL_URL}/oauth/v2/authorize`;
this.tokenEndpoint = `${ZITADEL_URL}/oauth/v2/token`;
this.redirectURI = 'http://localhost:4321/api/auth/callback';
}
async createAuthorizationURL(state: string, codeChallenge: string, scopes: string[]): Promise<URL> {
const url = new URL(this.authorizationEndpoint);
url.searchParams.set('response_type', 'code');
url.searchParams.set('client_id', ZITADEL_CLIENT_ID);
url.searchParams.set('redirect_uri', this.redirectURI);
url.searchParams.set('state', state);
url.searchParams.set('scope', scopes.join(' '));
url.searchParams.set('code_challenge_method', 'S256');
url.searchParams.set('code_challenge', codeChallenge);
return url;
}
async validateAuthorizationCode(code: string, codeVerifier: string) {
const response = await fetch(this.tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: ZITADEL_CLIENT_ID,
redirect_uri: this.redirectURI,
code,
code_verifier: codeVerifier,
}),
});
const tokens = await response.json();
// Optionally decode the ID token to get user claims
if (tokens.id_token) {
const claims = decodeJWT(tokens.id_token) as IdTokenClaims;
return { ...tokens, claims };
}
return tokens;
}
}

Implementing Authentication Endpoints

Sign-in Endpoint

Create pages/api/auth/signin.ts:

import type { APIRoute } from 'astro';
import { generateState, generateCodeChallenge } from 'arctic';
import { Zitadel } from '@/lib/zitadel';
export const prerender = false;
export const GET: APIRoute = async ({ cookies, redirect }) => {
const zitadel = new Zitadel();
const state = generateState();
const codeVerifier = generateCodeChallenge();
const codeChallenge = await generateCodeChallenge(codeVerifier);
// Store state and verifier in cookies for validation
cookies.set('state', state, {
httpOnly: true,
secure: import.meta.env.PROD,
sameSite: 'lax',
maxAge: 60 * 10, // 10 minutes
});
cookies.set('code_verifier', codeVerifier, {
httpOnly: true,
secure: import.meta.env.PROD,
sameSite: 'lax',
maxAge: 60 * 10,
});
const authUrl = await zitadel.createAuthorizationURL(
state,
codeChallenge,
['openid', 'profile', 'email']
);
return redirect(authUrl.toString());
};

Callback Endpoint

Create pages/api/auth/callback.ts:

import type { APIRoute } from 'astro';
import { Zitadel } from '@/lib/zitadel';
export const prerender = false;
export const GET: APIRoute = async ({ url, cookies, redirect }) => {
const code = url.searchParams.get('code');
const state = url.searchParams.get('state');
if (!code || !state) {
return new Response('Invalid request', { status: 400 });
}
const storedState = cookies.get('state')?.value;
const codeVerifier = cookies.get('code_verifier')?.value;
if (!storedState || !codeVerifier || state !== storedState) {
return new Response('Invalid state', { status: 400 });
}
// Clear temporary cookies
cookies.delete('state');
cookies.delete('code_verifier');
try {
const zitadel = new Zitadel();
const tokens = await zitadel.validateAuthorizationCode(code, codeVerifier);
// Store tokens in secure cookies
cookies.set('access_token', tokens.access_token, {
httpOnly: true,
secure: import.meta.env.PROD,
sameSite: 'lax',
maxAge: tokens.expires_in,
});
if (tokens.refresh_token) {
cookies.set('refresh_token', tokens.refresh_token, {
httpOnly: true,
secure: import.meta.env.PROD,
sameSite: 'lax',
maxAge: 60 * 60 * 24 * 30, // 30 days
});
}
return redirect('/');
} catch (error) {
console.error('Authentication error:', error);
return new Response('Authentication failed', { status: 500 });
}
};

Connecting the Login Button

Update your login button to trigger the authentication flow:

<a href="/api/auth/signin">Login with Zitadel</a>

Testing the Integration

  1. Click the login button
  2. You’ll be redirected to Zitadel’s authentication page
  3. Log in or register a new account
  4. After successful authentication, you’ll be redirected back to your application
  5. Check your browser’s developer tools to see the stored tokens

Managing Multiple Accounts

Zitadel has excellent multi-account support. Users can:

  • Switch between different accounts seamlessly
  • Register new accounts during the login flow
  • Manage their profiles and settings

As an administrator, you can:

  • View and manage all users in the Zitadel console
  • Verify email addresses
  • Reset passwords
  • Configure multi-factor authentication
  • Set up roles and permissions

Next Steps

Now that we have basic authentication working, in future videos we’ll explore:

  • Role-Based Access Control (RBAC)
  • Refresh token handling
  • User profile management
  • Social login providers
  • Advanced authorization patterns

Summary

Integrating Zitadel with Astro is straightforward thanks to:

  • The PKCE flow eliminating the need for client secrets
  • Arctic library handling OAuth complexity
  • Astro’s built-in support for server-side rendering and API routes

You can reuse the Zitadel class across multiple projects or publish it as a package for your team.

Transcript

Generated from English captions. Select a timestamp to jump to that moment.

0:01 David Flanagan: Welcome back. In this video we're gonna build on our previous video, I showed you how to set up a application and project that would allowed our sample application to log in and visualize the JWT that was returned so that we could see the user authenticated information including claims. Now, while that's useful for navigating the Zitadel dashboard, we also want to show you how you can integrate this into your own application. So in today's video, we're gonna take a look at how to hook up Zitadel using my favorite web framework, which is Astro. Most of what you're gonna see is applicable across other frameworks, but

0:46 fear not, we will be taking a look at some more options in the coming weeks. But let's kick things off with Zitadel integrated with Astro. Let's have some fun. All right, so the best place to start is by taking a look at what we have already. If I run ls you'll see that I have a source, public, astro.config, a few other bits and pieces. This was all created with bun create astro@latest. That is all. However, I did have Claude Code whip up a little bit of a design to improve the aesthetic of the application. If we pop over to the browser, hit refresh.

1:33 You just see it has modified the default Astro homepage with a Welcome to Zitadel demo, and it's added a login button, which click, click, click, click, click, click, click to use our Scottish term. It does heehaw, it does nothing. We need to hook this up and we're gonna do that together. we will leave our dev server running here, head over to VS Code, and the first thing we need to do is install a couple of dependencies. So let's tackle that first. So the first thing we need to do is open our package.json and come to our dependencies.

2:14 We need to add a library called Arctic. We can let VS Code work out the latest version. Hit save and then run bun install and that's it. It is pretty much the only dependency we need if we search for the Arctic project. You will see that this is just a bunch of helpers for working with OIDC and OAuth in any Node, JavaScript, TypeScript, Bun, Deno based project. It's a fantastic library and it's gonna make everything very, very simple for us to integrate with Astro today. The next thing we need to do is create a env, and I'm gonna add rc

2:58 because I really like to use direnv. It just keeps things nice and simple. We want to export our ZITADEL_CLIENT_ID, which will be a string, and we want to export a ZITADEL_URL, which is where our Zitadel instance can be found. We will grab both of these from the Zitadel console. This is the same Zitadel Cloud free instance that I used in a previous video to demo PKCE, and I still can't say that. We are gonna go to projects. Click on Rawkode Academy, and this is the React one we used last time, but today we are going to say Astro.

3:47 Choose web. Select PKCE, and then we're gonna put this in development mode. Input our port, and we'll need a callback address. So I'll just call this /auth/callback. I'm not worried about a post logout URL for now. When we create this, we are given our client id. Now, the fantastic thing about PKCE is that we don't need to handle any secret material. Meaning if you want to commit this client ID to your Git repository, public or not, you are perfectly safe to do so. It's a fantastic flow. I encourage you to use it. So now we can come over here and we can say that our client ID is now this.

4:39 We click close and what we want to grab is our Zitadel URL, which for Zitadel Cloud is here. If you're running this on Docker Compose, Kubernetes, or anything else; you just need to use the same URL that you use to log in to the console. With that envrc, I can do direnv allow and we'll see that these two environment variables are now available for me to consume within my application. Now I will have to restart my bun run dev server and allow direnv in this session so that my Astro application has access to both of these variables.

5:19 Now we can head over to our astro config where we do need to make some changes. We're first going to turn on output to server. We could do hybrid, but we do need some API endpoints, a nd you know if you wanted a fancy login button that is dynamic based on the user as they approach the page, you would have to use Astro server islands. This is not the point of this video. I'm just keeping things simple by using server. If you know what you're doing. Walk your own path. We can also use Astro Env to say that we have access to some certain properties.

6:00 We want our ZITADEL_URL, which is an envField of a string value. I like the Astro Env allows us to have, you know, slightly more sophisticated configuration even though it's coming from the environment. We can set the context for this and we can say that this is available on the server. Again, it's not secret. You could make this available on the client too, which is not a big deal, and we can set the access of this to public again, as not a secret material. We then have our client ID and we'll just do the exact same again here.

6:34 Now that I see a red squiggle I realized that I actually need to move all of this under schema. Copilots, get out the way for now. And that looks a little bit better. We can also turn on validate secrets to true, even though we don't have any. Just good practice for Astro Env. Now we move on to the slightly trickier component, although it's not that tricky, is that we need to provide something to handle our Zitadel configuration. First thing I'll do is just create something called lib with zitadel.ts. And to spare you the pain of watching me go clickety click, clickety click.

7:15 We'll use some movie magic where we'll skip to the final output of this file and we can go over it and review it in a sensible fashion just like that. So what do we have here? Well, we have the Astro Env where we're pulling in the two variables that we need. We have two dependencies that we haven't talked about yet, so I'll get to that in a minute. We have our Arctic dependencies, which allows us to handle what we allow that to handle most of the heavy lifting, not with the OAuth stuff. These two dependencies you may or may not need.

7:48 OsloJS just has some JWT helpers to allow us to decode the JWT and the oidc-clients- ts is really just using that as a type so we can get the basic skeleton of the claims without having to provide our own type or use any types or anything like that. We then have our Zitadel class. We have an authorizationEndpoint, our redirect, and our tokenEndpoint. We then have our createAuthorizationURL. So as a user attempts to log in, this function is gonna create the URL that we need to send as part of the redirect. And you can see here, it's just setting up the OIDC flow.

8:28 So it's saying that we want to get an access code, we have a client id. Dunno why that search parameters had the wrong casing. We then create our code challenge. Again, this is part of the PKCE flow and return to URL. This gives us everything that we need on the client side. Once we have the authorization URL, to just say, Hey, go and speak to Zitadel and come back when you have some sort of authorization code. That means we can trust that you say who you say you are. That isn't a weird sentence at all.

8:57 We then need a function to validate the authorization code that we get when they come back. So we just, you know, set the parameters, create an OAuth request, and then send this to the Zitadel server. This function here is using the optional stuff. This is if you do wish to get user information, you may not need, you may just be satisfied that you have an authenticated user and you can confirm that they are a user. However, you may want a little bit more information than their subject id, which is our user id. So that's where these optional libraries come in and where we can decode the

9:28 JWT, get the typed claims out, and then introspect them in some way. Again, completely optional, not something that you need, and it's entirely up to your use case. So you can decide whether that is a path that you need to go down. So let's open api/auth/sigin. No movie magic, just pre-configured fail, but we're gonna run through it. We pull in two functions from Arctic. We pull in our Zitadel and we've got some types from the astro with pre-render and set to false. Of course, this depends whether you're using server side, static, hybrid. I just like to set pre-render to false all the time so that if ever do

10:06 change the output method in the astro config, nothing breaks on the website. We instantiate Zitadel. We use the Arctic functions to get the code and the verifier, at least the state and the verifier. And then you'll see here we're just putting them into cookies. That just means we have access to them when we want to verify and validate any access token that we get from Zitadel, and we call our createAuthorizationURL function that we created in the Zitadel class w ith the scopes: openid, profile, and email. These are pretty much the default scopes. It gives you just enough information to ensure that you have a valid user.

10:44 We then just have a redirect. So the client will get redirected to the Zitadel server where they'll go through the authentication process like so. We then have callback.ts much the same: APIRoute, Zitadel class, pre-render false. This time we are expecting to receive some information on the URL. The first thing we do is grab the code and state, make sure they exist. Validate them and verify them against the cookie values. We're making sure there's no injection attacks or man in the middle. If we're happy with that, we can delete the cookies. And then we move on to the fun bit, which is instantiating Zitadel and then

11:27 calling our validateAuthorizationCode passing in the two values. So you can see here how we're using the two functions we created in the Zitadel. Just to validate things on the client side, and again, Arctic is doing all of the heavy lifting here. There's not really a lot for us to do if we get back a valid token. That is we don't get an error when we validateAuthorizationCode. We can then set the tokens that we get back from Zitadel into cookies so that they are available on subsequent requests if we have a refresh token and we'll cover

11:59 refresh tokens further on in the course. Then we also persist that and we just redirect to the homepage. It's all we need to do right now. That means if we open up components and welcome, this is our homepage. We can find the button for login. We can make this a anchor tag with an href, and copilot is already trying to jump in here and do everything for me. We can say /auth/signin, like so. Close that off. Grab the closing tag and wrap it around our button like so. This should already have reloaded. We can come back here and we can click login.

12:44 It took us back to the homepage, so one should assume that things are okay, but I don't expect you to trust me. We can open our dev tools, go to storage, and already we'll see here we have four different values, access, token, verifier id, and state. What I'm actually just gonna do is delete all of them. Pop open our Zitadel console. And log out. We'll go back to local host, click login, and now we get the Zitadel authentication flow. Now I could click on my admin user, or I can click other, where I could say, register and say Astro Demo astro@rawkode.academy,

13:31 we will save this password. Like so I can agree to the terms and the privacy policy and click next. That's gonna send me an email code. Now I could wait for that, but instead I'm gonna click go back because Zitadel has fantastic multi account support.. I'll login as my admin user. Go to users, we can now see that Astro demo is in an initial state. This means this user has not been verified. From here, we can resend to activation email, modify their username. Maybe I just want 'em to be astro. All of this is configurable in the organization settings will be

14:12 diving into that very, very soon. Can set nicknames, gender, language, and if I want I can modify their email address, say they got in touch and said, oh, I used the wrong email. Maybe it should have been a plus address. Click send. We can go into passwords, we can reset it, add multiple factors. We can do identity providers, authorization memberships, metadata. There's a whole bunch of stuff that we are gonna cover when it comes to user management and authorization, AuthZ, but that is for another video in this course. So I hope you see that integrating with Astro is super simple.

14:51 We create a class, you can reuse that across as many astro websites as you want, copy and paste, or publish it as an internal or public package. Maybe that's something I'll do in the future. And we're leaning into existing libraries like Arctic and others to make this almost child's play. I hope you find this useful. Join us for the next video as we take a look at more Zitadel features. Notably, next, we'll be taking a look at the RB AC model and authorization will see then.

Course curriculum (9 lessons)
  1. 01. Introduction
  2. 02. Prerequisites
  3. 03. How to Install Zitadel with Docker Compose (Step-by-Step)
  4. 04. Installing Zitadel on Kubernetes with Helm
  5. 05. Zitadel Cloud
  6. 06. Your First Application
  7. 07. Integrating with an Astro Application
  8. 08. Passwords, Passkeys, and MFA
  9. 09. Configuring OAuth Providers (Google, GitHub, etc.)

Loading optional course email signup. If it does not load, reload this lesson to retry. Signup requires JavaScript; all lesson content remains available without signing up.