Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
@clerk/astro
Advanced tools
Clerk is the easiest way to add authentication and user management to your Astro application. Add sign up, sign in, and profile management to your Astro application in minutes.
>=18.17.0
or laterAdd @clerk/astro
as a dependency
With npm
npm install @clerk/astro
With yarn
yarn add @clerk/astro
With pnpm
pnpm add @clerk/astro
To build the package locally with the TypeScript compiler, run:
npm run build
To build the package in watch mode, run the following:
npm run dev
PUBLIC_ASTRO_APP_CLERK_PUBLISHABLE_KEY=pk_(test|live)_xxxxxxx
CLERK_SECRET_KEY=sk_(test|live)_xxxxxxx
PUBLIC_ASTRO_APP_CLERK_SIGN_IN_URL=/sign-in # update this if sign in page exists on another path
PUBLIC_ASTRO_APP_CLERK_SIGN_UP_URL=/sign-up # update this if sign up page exists on another path
env.d.ts
/// <reference types="astro/client" />
/// <reference types="@clerk/astro/env" />
clerk
integration in your astro.config.mjs
file.@astrojs/react
and add the react
in your astro.config.mjs
file. You only need to perform this action if you are planing to use react with your project or the React features that provided by astro-clerk-auth
. Instructions@astrojs/node
package and the node
adapter in your astro.config.mjs
file. Instructionsoutput
to server
.Example configuration file
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
import node from '@astrojs/node';
import clerk from '@clerk/astro';
export default defineConfig({
integrations: [
react(),
clerk({
afterSignInUrl: '/',
afterSignUpUrl: '/',
}),
],
output: 'server',
adapter: node({
mode: 'standalone',
}),
});
This step is required in order to use SSR or any control component. Create a middleware.ts
file inside the src/
directory.
Simple use
import { clerkMiddleware } from '@clerk/astro/server';
export const onRequest = clerkMiddleware();
Supports chaining with sequence
const greeting = defineMiddleware(async (context, next) => {
console.log('greeting request');
console.log(context.locals.auth());
const response = await next();
console.log('greeting response');
return response;
});
export const onRequest = sequence(clerkMiddleware(), greeting);
Advanced use with handler
const isProtectedPage = createRouteMatcher(['/user(.*)', '/discover(.*)', /^\/organization/]);
export const onRequest = clerkMiddleware((auth, context, next) => {
const requestURL = new URL(context.request.url);
if (['/sign-in', '/', '/sign-up'].includes(requestURL.pathname)) {
return next();
}
if (isProtectedPage(context.request) && !auth().userId) {
return auth().redirectToSignIn();
}
if (!auth().orgId && requestURL.pathname !== '/discover' && requestURL.pathname === '/organization') {
const searchParams = new URLSearchParams({
redirectUrl: requestURL.href,
});
const orgSelection = new URL(`/discover?${searchParams.toString()}`, context.request.url);
return context.redirect(orgSelection.href);
}
return next();
});
Supported components
All of the above can be used with React or Vanilla JS. The only difference is the import path.
// Import UserProfile build with React (requires `@astro/react`)
import { UserProfile } from '@clerk/astro/client/react';
// Import UserButton build with vanilla JS
import { UserProfile } from '@clerk/astro/components/interactive';
Pages that include a Clerk UI component need to be wrapped with ClerkLayout
, as shown above.
Supported components
All of the above can be used with React or only on server. The only difference is the import path.
// Import Protect build with React (requires `@astro/react`)
import { Protect } from '@clerk/astro/client/react';
// Import SignedIn build server side code
import { SignedIn } from '@clerk/astro/components/control';
In this example we are fetching the logged in user.
import type { APIRoute } from 'astro';
const unautorized = () =>
new Response(JSON.stringify({ error: 'unathorized access' }), {
status: 401,
});
export const GET: APIRoute = async ({ locals }) => {
if (!locals.auth().userId) {
return unautorized();
}
return new Response(JSON.stringify(await locals.currentUser()), {
status: 200,
});
};
Astro.locals.auth()
to retrieve the Authentication ObjectExample SignedIn React component that supports SSR
import type { PropsWithChildren } from 'react';
import { useAuth } from '@clerk/astro/client/react';
export function SignedIn(props: PropsWithChildren) {
const { userId } = useAuth();
if (!userId) {
return null;
}
return props.children;
}
Warning: SSR not supported
import type { PropsWithChildren } from 'react';
import { useStore } from '@nanostores/react';
import { $authStore } from '@clerk/astro/client/stores';
export function SignedOut(props: PropsWithChildren) {
const { userId } = useStore($authStore);
if (userId) {
return null;
}
return props.children;
}
Example Header react component that uses Clerk components
import { SignedIn, SignedOut, UserButton } from '@clerk/astro/client/react';
export function Header() {
return (
<header>
<h1>My App</h1>
<SignedIn>
<UserButton />
</SignedIn>
<SignedOut>
<a href='/sign-in'>Go to Sign in</a>
</SignedOut>
</header>
);
}
Clerk Headless mode (see ClerkJSVariant
prop their docs) is a Clerk variant that is focused towards getting smaller bundle sizes. This variant does not include React or any client side components for Clerk (e.g. their signin component). Because of that the bundle size is drastically smaller. On top of that it also lazy loads the JavaScript client side.
In order to use headless mode with this package, change your Astro configuration file to:
import { defineConfig } from "astro/config";
import react from "@astrojs/react";
import node from "@astrojs/node";
- import clerk from "@clerk/astro";
+ import clerk from "@clerk/astro/hotload";
export default defineConfig({
integrations: [
react(),
clerk({
+ clerkJSVariant: "headless"
}),
],
output: "server",
adapter: node({
mode: "standalone",
}),
});
You can get in touch with us in any of the following ways:
We're open to all community contributions! If you'd like to contribute in any way, please read our contribution guidelines) .
@clerk/astro
follows good practices of security, but 100% security cannot be assured.
@clerk/astro
is provided "as is" without any warranty. Use at your own risk.
For more information and to report security issues, please refer to our security documentation.
This project is licensed under the MIT license.
See LICENSE for more information.
FAQs
Clerk SDK for Astro
The npm package @clerk/astro receives a total of 1,747 weekly downloads. As such, @clerk/astro popularity was classified as popular.
We found that @clerk/astro demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 8 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.