@supermemory/authkit-remix-cloudflare
v0.0.19
Published
Cloudflare-Compatible auth and session helpers for using WorkOS & AuthKit with Remix
Downloads
66
Readme
AuthKit Remix Library (that works with Cloudflare)
This is a fork of https://github.com/supermemory/authkit-remix-cloudflare, to make it compatible with workers runtime.
Reason: We had some projects where we wanted to use authkit with remix, but we are using cloudflare for deployment.
The reason it didn't work was because the library was using @remix-run/node
and using environment variables from process.env
instead of context.env
.
So, I simply forked it and made the changes to make it compatible with cloudflare.
The AuthKit library for Remix provides convenient helpers for authentication and session management using WorkOS & AuthKit with Remix. You can find this library in action in the remix-authkit-example repo.
Installation
Install the package with:
npm i @supermemory/authkit-remix-cloudflare
or
yarn add @supermemory/authkit-remix-cloudflare
Pre-flight
Make sure the following values are present in your .dev.vars
environment variables file. The client ID and API key can be found in the WorkOS dashboard, and the redirect URI can also be configured there.
WORKOS_CLIENT_ID="client_..." # retrieved from the WorkOS dashboard
WORKOS_API_KEY="sk_test_..." # retrieved from the WorkOS dashboard
WORKOS_REDIRECT_URI="http://localhost:5173/callback" # configured in the WorkOS dashboard
WORKOS_COOKIE_PASSWORD="<your password>" # generate a secure password here
WORKOS_COOKIE_PASSWORD
is the private key used to encrypt the session cookie. It has to be at least 32 characters long. You can use the 1Password generator or the openssl
library to generate a strong password via the command line:
openssl rand -base64 24
To use the signOut
method, you'll need to set your app's homepage in your WorkOS dashboard settings under "Redirects".
Optional configuration
Certain environment variables are optional and can be used to debug or configure cookie settings.
WORKOS_COOKIE_MAX_AGE='600' # maximum age of the cookie in seconds. Defaults to 400 days
WORKOS_API_HOSTNAME='api.workos.com' # base WorkOS API URL
WORKOS_API_HTTPS=true # whether to use HTTPS in API calls
WORKOS_API_PORT=5173 # port to use for API calls
Setup
Callback route
AuthKit requires that you have a callback URL to redirect users back to after they've authenticated. In your Remix app, create a new route and add the following:
import { authLoader } from '@supermemory/authkit-remix-cloudflare';
export const loader = authLoader();
Make sure this route matches the WORKOS_REDIRECT_URI
variable and the configured redirect URI in your WorkOS dashboard. For instance if your redirect URI is http://localhost:2884/callback
then you'd put the above code in /app/routes/callback.ts
.
You can also control the pathname the user will be sent to after signing-in by passing a returnPathname
option to authLoader
like so:
export const loader = authLoader({ returnPathname: '/dashboard' });
Usage
Access authentication data in your Remix application
Use authkitLoader
to configure AuthKit for your Remix application routes.
import type { LoaderFunctionArgs } from '@remix-run/cloudflare';
import { authkitLoader } from '@supermemory/authkit-remix-cloudflare';
export const loader = (args: LoaderFunctionArgs) => authkitLoader(args);
export function App() {
return (
<div>
<p>Welcome back {user?.firstName && `, ${user?.firstName}`}</p>
</div>
);
}
For pages where you want to display a signed-in and signed-out view, use authkitLoader
to retrieve the user profile from WorkOS. You can pass in additional data by providing a loader function directly to authkitLoader
.
import type { ActionFunctionArgs, LoaderFunctionArgs } from '@remix-run/cloudflare';
import { json } from '@remix-run/cloudflare';
import { Form, Link, useLoaderData } from '@remix-run/react';
import { getSignInUrl, getSignUpUrl, signOut, authkitLoader } from '@supermemory/authkit-remix-cloudflare';
export const loader = (args: LoaderFunctionArgs) =>
authkitLoader(args, async ({ request, auth, context }) => {
return json({
signInUrl: await getSignInUrl(),
signUpUrl: await getSignUpUrl(),
});
});
export async function action({ request, context }: ActionFunctionArgs) {
return await signOut(request, context);
}
export default function HomePage() {
// Retrieves the user from the session or returns `null` if no user is signed in
// Other supported values include sessionId, accessToken, organizationId, role, permissions and impersonator
const { user, signInUrl, signUpUrl } = useLoaderData<typeof loader>();
if (!user) {
return (
<>
<Link to={signInUrl}>Log in</Link>
<br />
<Link to={signUpUrl}>Sign Up</Link>
</>
);
}
return (
<Form method="post">
<p>Welcome back {user?.firstName && `, ${user?.firstName}`}</p>
<button type="submit">Sign out</button>
</Form>
);
}
Requiring auth
For pages where a signed-in user is mandatory, you can use the ensureSignedIn
option:
export const loader = (args: LoaderFunctionArgs) => authkitLoader(args, { ensureSignedIn: true });
Enabling ensureSignedIn
will redirect users to AuthKit if they attempt to access the page without being authenticated.
Signing out
Use the signOut
method to sign out the current logged in user, end the session, and redirect to your app's homepage. The homepage redirect is set in your WorkOS dashboard settings under "Redirect".
Get the access token
Sometimes it is useful to obtain the access token directly, for instance to make API requests to another service.
import type { LoaderFunctionArgs } from '@remix-run/cloudflare';
import { json } from '@remix-run/cloudflare';
import { authkitLoader } from '@supermemory/authkit-remix-cloudflare';
export const loader = (args: LoaderFunctionArgs) =>
authkitLoader(args, async ({ auth }) => {
const { accessToken } = auth;
if (!accessToken) {
// Not signed in
}
const serviceData = await fetch('/api/path', {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
return json({
data: serviceData,
});
});
[addition]
Getting the current session from loader or action using request
Apart from the ones by workos, I have also added this function to help get the current session from loader or action using request
and context
const session = await getSessionFromRequest(request, context);
Debugging
To enable debug logs, pass in the debug flag when using authkitLoader
.
import { authkitLoader } from '@supermemory/authkit-remix-cloudflare';
export const loader = (args: LoaderFunctionArgs) => authkitLoader(args, { debug: true });
If providing a loader function, you can pass the options object as the third parameter
import { authkitLoader } from '@supermemory/authkit-remix-cloudflare';
export const loader = (args: LoaderFunctionArgs) =>
authkitLoader(
args,
async ({ auth }) => {
return json({ foo: 'bar' });
},
{ debug: true },
);