Skip to content

Commit 287bbab

Browse files
author
Paul Asjes
committed
Update readme
1 parent 413c63d commit 287bbab

File tree

1 file changed

+63
-99
lines changed

1 file changed

+63
-99
lines changed

README.md

Lines changed: 63 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
11
# AuthKit Remix Library
22

3-
The AuthKit library for Next.js provides convenient helpers for authentication and session management using WorkOS & AuthKit with Next.js.
3+
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](https://github.com/workos/remix-authkit-example) repo.
44

55
## Installation
66

77
Install the package with:
88

99
```
10-
npm i @workos-inc/authkit-nextjs
10+
npm i @workos-inc/authkit-remix
1111
```
1212

1313
or
1414

1515
```
16-
yarn add @workos-inc/authkit-nextjs
16+
yarn add @workos-inc/authkit-remix
1717
```
1818

1919
## Pre-flight
@@ -50,57 +50,60 @@ WORKOS_API_PORT=3000 # port to use for API calls
5050

5151
### Callback route
5252

53-
WorkOS requires that you have a callback URL to redirect users back to after they've authenticated. In your Next.js app, [expose an API route](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) and add the following.
53+
WorkOS requires that you have a callback URL to redirect users back to after they've authenticated. In your Remix app, [create a new route](https://remix.run/docs/en/main/discussion/routes), name it `callback.tsx` and add the following.
5454

5555
```ts
56-
import { handleAuth } from '@workos-inc/authkit-nextjs';
56+
import { authLoader } from '@workos-inc/authkit-remix';
5757

58-
export const GET = handleAuth();
58+
export const loader = authLoader();
5959
```
6060

61-
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:3000/auth/callback` then you'd put the above code in `/app/auth/callback/route.ts`.
61+
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:3000/auth/callback` then you'd put the above code in `/app/routes/callback.ts`.
6262

63-
You can also control the pathname the user will be sent to after signing-in by passing a `returnPathname` option to `handleAuth` like so:
63+
You can also control the pathname the user will be sent to after signing-in by passing a `returnPathname` option to `authLoader` like so:
6464

6565
```ts
66-
export const GET = handleAuth({ returnPathname: '/dashboard' });
67-
```
68-
69-
### Middleware
70-
71-
This library relies on [Next.js middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware) to provide session management for routes. Put the following in your `middleware.ts` file in the root of your project:
72-
73-
```ts
74-
import { authkitMiddleware } from '@workos-inc/authkit-nextjs';
75-
76-
export default authkitMiddleware();
77-
78-
// Match against pages that require auth
79-
// Leave this out if you want auth on every resource (including images, css etc.)
80-
export const config = { matcher: ['/', '/admin'] };
66+
export const loader = authLoader({ returnPathname: '/dashboard' });
8167
```
8268

8369
## Usage
8470

8571
### Get the current user
8672

87-
For pages where you want to display a signed-in and signed-out view, use `getUser` to retrieve the user profile from WorkOS.
73+
For pages where you want to display a signed-in and signed-out view, use `withAuth` to retrieve the user profile from WorkOS.
8874

8975
```jsx
90-
import Link from 'next/link';
91-
import { getSignInUrl, getSignUpUrl, getUser, signOut } from '@workos-inc/authkit-nextjs';
76+
import type {
77+
ActionFunctionArgs,
78+
LoaderFunctionArgs,
79+
} from '@remix-run/node';
80+
import {
81+
Link,
82+
useRouteLoaderData,
83+
json,
84+
Form,
85+
} from '@remix-run/react';
86+
import { getSignInUrl, getSignUpUrl, withAuth, signOut } from '@workos-inc/authkit-remix';
87+
88+
export async function loader({ request }: LoaderFunctionArgs) {
89+
const { user } = await withAuth(request);
90+
91+
return json({
92+
signInUrl: await getSignInUrl(),
93+
signUpUrl: await getSignUpUrl(),
94+
user,
95+
});
96+
}
9297

93-
export default async function HomePage() {
98+
export async function action({ request }: ActionFunctionArgs) {
99+
return await signOut(request);
100+
}
101+
102+
export default function HomePage() {
94103
// Retrieves the user from the session or returns `null` if no user is signed in
95-
const { user } = await getUser();
104+
const { user, signInUrl, signUpUrl } = useLoaderData<typeof loader>();
96105

97106
if (!user) {
98-
// Get the URL to redirect the user to AuthKit to sign in
99-
const signInUrl = await getSignInUrl();
100-
101-
// Get the URL to redirect the user to AuthKit to sign up
102-
const signUpUrl = await getSignUpUrl();
103-
104107
return (
105108
<>
106109
<Link href={signInUrl}>Log in</Link>
@@ -110,15 +113,10 @@ export default async function HomePage() {
110113
}
111114

112115
return (
113-
<form
114-
action={async () => {
115-
'use server';
116-
await signOut();
117-
}}
118-
>
116+
<Form method="post">
119117
<p>Welcome back {user?.firstName && `, ${user?.firstName}`}</p>
120118
<button type="submit">Sign out</button>
121-
</form>
119+
</Form>
122120
);
123121
}
124122
```
@@ -128,68 +126,28 @@ export default async function HomePage() {
128126
For pages where a signed-in user is mandatory, you can use the `ensureSignedIn` option:
129127
130128
```jsx
131-
const { user } = await getUser({ ensureSignedIn: true });
129+
const { user } = await withAuth({ ensureSignedIn: true });
132130
```
133131
134132
Enabling `ensureSignedIn` will redirect users to AuthKit if they attempt to access the page without being authenticated.
135133
136-
### Middleware auth
137-
138-
The default behavior of this library is to request authentication via the `getUser` method on a per-page basis. There are some use cases where you don't want to call `getUser` (e.g. you don't need user data for your page) or if you'd prefer a "secure by default" approach where every route defined in your middleware matcher is protected unless specified otherwise. In those cases you can opt-in to use middleware auth instead:
139-
140-
```ts
141-
import { authkitMiddleware } from '@workos-inc/authkit-nextjs';
142-
143-
export default authkitMiddleware({
144-
middlewareAuth: {
145-
enabled: true,
146-
unauthenticatedPaths: ['/', '/about'],
147-
},
148-
});
149-
150-
// Match against pages that require auth
151-
// Leave this out if you want auth on every resource (including images, css etc.)
152-
export const config = { matcher: ['/', '/admin/:path*', '/about'] };
153-
```
154-
155-
In the above example the `/admin` page will require a user to be signed in, whereas `/` and `/about` can be accessed without signing in.
156-
157-
`unauthenticatedPaths` uses the same glob logic as the [Next.js matcher](https://nextjs.org/docs/pages/building-your-application/routing/middleware#matcher).
158-
159134
### Signing out
160135
161-
Use the `signOut` method to sign out the current logged in user and redirect to your app's homepage. The homepage redirect is set in your WorkOS dashboard settings under "Redirect".
162-
163-
### Visualizing an impersonation
164-
165-
Render the `Impersonation` component in your app so that it is clear when someone is [impersonating a user](https://workos.com/docs/user-management/impersonation).
166-
The component will display a frame with some information about the impersonated user, as well as a button to stop impersonating.
167-
168-
```jsx
169-
import { Impersonation } from '@workos-inc/authkit-nextjs';
170-
171-
export default function App() {
172-
return (
173-
<div>
174-
<Impersonation />
175-
{/* Your app content */}
176-
</div>
177-
);
178-
}
179-
```
136+
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".
180137
181138
### Get the access token
182139
183140
Sometimes it is useful to obtain the access token directly, for instance to make API requests to another service.
184141
185142
```jsx
186-
import { getUser } from '@workos-inc/authkit-nextjs';
143+
import type { LoaderFunctionArgs, json } from '@remix-run/node';
144+
import { withAuth } from '@workos-inc/authkit-remix';
187145
188-
export default async function HomePage() {
189-
const { accessToken } = await getUser();
146+
export async function loader({ request }: LoaderFunctionArgs) {
147+
const { accessToken } = await withAuth(request);
190148
191-
if (!accessToken) {
192-
return <div>Not signed in</div>;
149+
if (!accesstoken) {
150+
// Not signed in
193151
}
194152
195153
const serviceData = await fetch('/api/path', {
@@ -198,22 +156,28 @@ export default async function HomePage() {
198156
},
199157
});
200158
201-
return <div>{serviceData}</div>;
159+
return json({
160+
data: serviceData,
161+
});
202162
}
203163
```
204164
205165
### Debugging
206166
207-
To enable debug logs, initialize the middleware with the debug flag enabled.
167+
To enable debug logs, pass in the debug flag when using `withAuth`.
208168
209169
```js
210-
import { authkitMiddleware } from '@workos-inc/authkit-nextjs';
211-
212-
export default authkitMiddleware({ debug: true });
213-
```
214-
215-
### Troubleshooting
170+
import { withAuth, getSignInUrl, getSignUpUrl } from '@workos-inc/authkit-remix';
216171
217-
#### NEXT_REDIRECT error when using try/catch blocks
172+
export async function loader({ request }: LoaderFunctionArgs) {
173+
const { user } = await withAuth(request, {
174+
debug: true,
175+
});
218176
219-
Wrapping a `getUser({ ensureSignedIn: true })` call in a try/catch block will cause a `NEXT_REDIRECT` error. This is because `getUser` will attempt to redirect the user to AuthKit if no session is detected and redirects in Next must be [called outside a try/catch](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#redirecting).
177+
return json({
178+
signInUrl: await getSignInUrl(),
179+
signUpUrl: await getSignUpUrl(),
180+
user,
181+
});
182+
}
183+
```

0 commit comments

Comments
 (0)