npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

astro-clerk-auth

v0.11.0

Published

Unofficial package Clerk SDK for Asto

Downloads

147

Readme

astro-clerk-auth

Community package that integrates Clerk with Astro

[!IMPORTANT] This project has graduated to an official SDK. Please proceed here for migration instructions.

Live Demo

Online Demo

Report Issues

If you are experiencing issues please submit them via the Issues page in GH. As this SDK is not officially suppported by Clerk or Astro, contacting them directly for issues regarding this package might cause your requests to be unanswered.

Install package

Add astro-clerk-auth as a dependency

With npm

npm install astro-clerk-auth

With yarn

yarn add astro-clerk-auth

With pnpm

pnpm add astro-clerk-auth

Set environment variables

PUBLIC_ASTRO_APP_CLERK_PUBLISHABLE_KEY=pk_test_xxxxxxxx
CLERK_SECRET_KEY=sk_test_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

Update env.d.ts

/// <reference types="astro/client" />
/// <reference types="astro-clerk-auth/env" />

Add integrations

  • Add the clerk integration in your astro.config.mjs file.
  • (Optional) Install the @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
  • Install the @astrojs/node package and the node adapter in your astro.config.mjs file. Instructions
  • Set output to server.

Example configuration file

import { defineConfig } from "astro/config";
import react from "@astrojs/react";
import node from "@astrojs/node";
import clerk from "astro-clerk-auth";

export default defineConfig({
  integrations: [
    react(),
    clerk({
      afterSignInUrl: "/",
      afterSignUpUrl: "/",
    }),
  ],
  output: "server",
  adapter: node({
    mode: "standalone",
  }),
});

Add a middleware file

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 "astro-clerk-auth/server";

export const onRequest = clerkMiddleware();

Supports chaining with sequence

import { clerkMiddleware } from "astro-clerk-auth/server";

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

import { clerkMiddleware, createRouteMatcher } from "astro-clerk-auth/server";

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();
});

Use Clerk UI Components

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 'astro-clerk-auth/components/react'

// Import UserButton build with vanilla JS
import { UserProfile } from 'astro-clerk-auth/components/interactive'

Pages that include a Clerk UI component need to be wrapped with ClerkLayout, as shown above.

Use Clerk Control Components

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 'astro-clerk-auth/components/react'

// Import SignedIn build server side code
import { SignedIn } from 'astro-clerk-auth/components/control'

Protect your API Routes

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,
  });
};

Use Astro.locals

Use clerkClient to access Backend API

Use the clerkClient utility to get access to Clerk's Backend API and perform administrative actions. clerkClient is a function that accepts the astro context as its argument.

Endpoint

import type { APIRoute } from "astro";
import { clerkClient } from "astro-clerk-auth/server"

export const GET: APIRoute = async (context) => {
  ...
  clerkClient(context).users.getUser(...)
  ...
};

Astro Page

---
import { clerkClient } from "astro-clerk-auth/server"
...
clerkClient(Astro).users.getUser(...)
---

Deep dive

Use Clerk react hooks

Example SignedIn React component that supports SSR

import type { PropsWithChildren } from 'react';
import { useAuth } from 'astro-clerk-auth/client/react';

export function SignedIn(props: PropsWithChildren) {
  const { userId } = useAuth()

  if (!userId) {
    return null;
  }
  return props.children;
}

Use a client store to build your custom logic

Warning: SSR not supported

import type { PropsWithChildren } from 'react';
import { useStore } from '@nanostores/react';
import { $authStore } from 'astro-clerk-auth/client/stores';

export function SignedOut(props: PropsWithChildren) {
  const { userId } = useStore($authStore);

  if (userId) {
    return null;
  }
  return props.children;
}

Use Clerk react components inside your components

Example Header react component that uses Clerk components

import { SignedIn, SignedOut, UserButton } from 'astro-clerk-auth/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>
  );
}

Use Clerk in Headless Mode

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 "astro-clerk-auth";
+ import clerk from "astro-clerk-auth/hotload";

export default defineConfig({
  integrations: [
    react(),
    clerk({
+      clerkJSVariant: "headless"
    }),
  ],
  output: "server",
  adapter: node({
    mode: "standalone",
  }),
});