Package Exports
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@temporal.ai/auth-clerk) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@temporal.ai/auth-clerk
Production-ready Clerk authentication integration for React and Express applications. Simplify your authentication workflow with TypeScript-first, zero-configuration setup.
Features
✅ React Hooks - Authenticated API calls with automatic token management
✅ Express Middleware - JWT verification and user context
✅ Route Protection - Components for protecting React routes
✅ TypeScript First - Full type safety out of the box
✅ Zero Config - Works with sensible defaults
✅ Production Ready - Error handling, loading states, and optimization
Quick Start
Installation
npm install @temporal.ai/auth-clerkReact Setup
import { ClerkProvider } from '@clerk/clerk-react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useAuthenticatedApi, ProtectedRoute } from '@temporal.ai/auth-clerk';
function Dashboard() {
const { useAuthenticatedQuery } = useAuthenticatedApi();
const { data: profile } = useAuthenticatedQuery(['/api/user/profile']);
return <div>Welcome, {profile?.firstName}!</div>;
}
function App() {
return (
<ClerkProvider publishableKey={process.env.REACT_APP_CLERK_PUBLISHABLE_KEY}>
<QueryClientProvider client={new QueryClient()}>
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
</QueryClientProvider>
</ClerkProvider>
);
}Express Setup
const express = require('express');
const { requireAuth } = require('@temporal.ai/auth-clerk');
const app = express();
app.get('/api/user/profile', requireAuth(), (req, res) => {
res.json({ userId: req.userId });
});API Reference
React Hooks
useAuthenticatedApi(options?)
Hook for making authenticated API calls with automatic token management.
const { useAuthenticatedQuery, useAuthenticatedMutation, authenticatedFetch } = useAuthenticatedApi({
baseUrl: '/api',
defaultHeaders: { 'Custom-Header': 'value' }
});Options:
baseUrl?: string- Base URL for API callsdefaultHeaders?: Record<string, string>- Default headers for all requests
Returns:
useAuthenticatedQuery<T>(queryKey, enabled?, options?)- React Query with authuseAuthenticatedMutation<TData, TVariables>(url, method?, options?)- Mutation with authauthenticatedFetch(url, options?)- Raw fetch with authentication
Components
<ProtectedRoute>
Component that protects routes and requires authentication.
<ProtectedRoute
fallback={<div>Access denied</div>}
requireEmailVerified={true}
customCheck={(user) => user.role === 'admin'}
>
<Dashboard />
</ProtectedRoute>Props:
children: ReactNode- Content to show when authenticatedfallback?: ReactNode- Content to show when access is deniedrequireEmailVerified?: boolean- Require verified emailcustomCheck?: (user) => boolean- Custom authorization logic
<AuthGate>
Simple gate that shows children only when authenticated.
<AuthGate fallback={<SignInButton />}>
<UserProfile />
</AuthGate>Express Middleware
requireAuth(options?)
Middleware to verify Clerk JWT tokens and add user info to request.
app.get('/protected', requireAuth({
includeUserData: true,
onAuthError: (error, req, res) => {
res.status(401).json({ message: 'Custom error handling' });
}
}), (req, res) => {
console.log(req.userId, req.clerkUser);
});Options:
includeUserData?: boolean- Fetch full user data from ClerkonAuthError?: (error, req, res) => void- Custom error handlergetToken?: (req) => string- Custom token extraction
requireUserInDatabase(getUserFn)
Middleware to ensure user exists in your database.
app.get('/settings',
requireAuth(),
requireUserInDatabase(clerkId => db.getUserByClerkId(clerkId)),
(req, res) => {
// req.user is guaranteed to exist
res.json(req.user);
}
);Examples
Full React Example
Check out examples/react-example.tsx for a complete implementation with:
- Dashboard with user profile
- Protected routes
- Landing page with conditional auth
- Mutation examples
Full Express Example
Check out examples/express-example.js for a complete backend with:
- User profile endpoints
- Database integration
- Custom authentication flows
- Error handling
TypeScript Support
This package is built with TypeScript and includes full type definitions. All hooks and components are fully typed for the best developer experience.
// Types are automatically inferred
const { data: profile } = useAuthenticatedQuery<UserProfile>(['/api/profile']);
const mutation = useAuthenticatedMutation<UpdateResponse, UpdateRequest>('/api/update');License
MIT © Temporal AI Technologies
Contributing
Issues and pull requests are welcome! Please visit our GitHub repository.