Skip to content

Latest commit

 

History

History
 
 

hono

README.md


@clerk/hono

Getting Started

Clerk is the easiest way to add authentication and user management to your Hono application. Add sign up, sign in, and profile management to your application in minutes.

Prerequisites

  • Hono 4+
  • Node.js >=20.9.0 or later

Installation

npm install @clerk/hono

Configuration

Set your Clerk API keys as environment variables:

CLERK_SECRET_KEY=sk_****
CLERK_PUBLISHABLE_KEY=pk_****

Usage

import { Hono } from 'hono';
import { clerkMiddleware, getAuth } from '@clerk/hono';

const app = new Hono();

// Apply Clerk middleware to all routes
app.use('*', clerkMiddleware());

// Public route
app.get('/', c => {
  return c.json({ message: 'Hello!' });
});

// Protected route
app.get('/protected', c => {
  const { userId } = getAuth(c);

  if (!userId) {
    return c.json({ error: 'Unauthorized' }, 401);
  }

  return c.json({ message: 'Hello authenticated user!', userId });
});

export default app;

Accessing the Clerk Client

You can access the Clerk Backend API client directly from the context:

app.get('/user/:id', async c => {
  const clerkClient = c.get('clerk');
  const user = await clerkClient.users.getUser(c.req.param('id'));
  return c.json({ user });
});

Using acceptsToken for Machine Auth

app.get('/api', c => {
  const auth = getAuth(c, { acceptsToken: 'api_key' });

  if (!auth.userId) {
    return c.json({ error: 'Unauthorized' }, 401);
  }

  return c.json({ message: 'API access granted' });
});

Webhook Verification

import { Hono } from 'hono';
import { verifyWebhook } from '@clerk/hono/webhooks';

const app = new Hono();

app.post('/webhooks/clerk', async c => {
  const evt = await verifyWebhook(c);

  switch (evt.type) {
    case 'user.created':
      console.log('User created:', evt.data.id);
      break;
    // Handle other event types...
  }

  return c.json({ received: true });
});

Support

For help, visit our support page.

Community

Join our Discord community to connect with other developers.

Contributing

We're open to all community contributions! If you'd like to contribute in any way, please read our contribution guidelines and code of conduct.

Security

@clerk/hono follows good practices of security, but 100% security cannot be assured.

@clerk/hono 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.

License

This project is licensed under the MIT license.

See LICENSE for more information.