@lumoauth/nextjs 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +394 -78
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,147 +1,463 @@
|
|
|
1
1
|
# @lumoauth/nextjs
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@lumoauth/nextjs)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
|
|
6
|
+
`@lumoauth/nextjs` adds LumoAuth sign-in to a Next.js App Router app. Your server runs the OAuth
|
|
7
|
+
flow and keeps the session in an encrypted httpOnly cookie. Because the server can read that
|
|
8
|
+
cookie, a server component can read who the user is before it renders. Signed-in pages arrive
|
|
9
|
+
correct on the first paint, with no flash of signed-out content.
|
|
10
|
+
|
|
11
|
+
The package has two entry points:
|
|
12
|
+
|
|
13
|
+
- `@lumoauth/nextjs/server` is for server code: `auth()`, `currentUser()`, `protectPage()`, the
|
|
14
|
+
route handler and the middleware.
|
|
15
|
+
- `@lumoauth/nextjs` is for client components. It re-exports every component and hook from
|
|
16
|
+
[`@lumoauth/react`](../react/README.md) and adds `<LumoAuthNextProvider>`.
|
|
17
|
+
|
|
18
|
+
It is part of the [LumoAuth JavaScript SDK](../../README.md).
|
|
19
|
+
|
|
20
|
+
## Contents
|
|
21
|
+
|
|
22
|
+
- [Is this the right package?](#is-this-the-right-package)
|
|
23
|
+
- [Requirements](#requirements)
|
|
24
|
+
- [Install](#install)
|
|
25
|
+
- [Quick start](#quick-start)
|
|
26
|
+
- [Core concepts](#core-concepts)
|
|
27
|
+
- [Configuration](#configuration)
|
|
28
|
+
- [Guides](#guides)
|
|
29
|
+
- [Read the session in server code](#read-the-session-in-server-code)
|
|
30
|
+
- [Protect pages](#protect-pages)
|
|
31
|
+
- [Call LumoAuth or your API with the user's token](#call-lumoauth-or-your-api-with-the-users-token)
|
|
32
|
+
- [Use components and hooks in client components](#use-components-and-hooks-in-client-components)
|
|
33
|
+
- [Request more scopes](#request-more-scopes)
|
|
34
|
+
- [How the session is protected](#how-the-session-is-protected)
|
|
35
|
+
- [Sessions and access tokens](#sessions-and-access-tokens)
|
|
36
|
+
- [API reference](#api-reference)
|
|
37
|
+
- [Troubleshooting](#troubleshooting)
|
|
38
|
+
- [Limitations](#limitations)
|
|
39
|
+
- [Versioning and compatibility](#versioning-and-compatibility)
|
|
40
|
+
- [Related packages](#related-packages)
|
|
41
|
+
- [Licence](#licence)
|
|
42
|
+
|
|
43
|
+
## Is this the right package?
|
|
44
|
+
|
|
45
|
+
| You are building… | Use |
|
|
46
|
+
|---|---|
|
|
47
|
+
| A Next.js 14+ App Router app | **This package** |
|
|
48
|
+
| A Next.js app with the Pages Router | Not supported yet. Use [`@lumoauth/react`](../react/README.md). |
|
|
49
|
+
| A React app without Next.js | [`@lumoauth/react`](../react/README.md) |
|
|
50
|
+
| An Express server | [`@lumoauth/express`](../express/README.md) |
|
|
51
|
+
|
|
52
|
+
## Requirements
|
|
53
|
+
|
|
54
|
+
- Next.js 14 or newer, with the App Router
|
|
55
|
+
- React 18 or newer
|
|
56
|
+
- Node 18 or newer. The cookie code uses Web Crypto, so it also runs in the edge runtime.
|
|
57
|
+
- A LumoAuth organization and an OAuth client. Register the callback URL
|
|
58
|
+
(`<your origin>/api/auth/callback`) as a redirect URI. Register your sign-out landing page
|
|
59
|
+
(by default `<your origin>/`) as a post-logout redirect URI.
|
|
60
|
+
|
|
61
|
+
## Install
|
|
5
62
|
|
|
6
|
-
|
|
63
|
+
```bash
|
|
64
|
+
npm install @lumoauth/nextjs
|
|
65
|
+
```
|
|
7
66
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
paint is always signed-out and corrects itself after hydration. That is the
|
|
11
|
-
flash.
|
|
67
|
+
`next` and `react` are peer dependencies. `@lumoauth/react` and `@lumoauth/client` are installed
|
|
68
|
+
with this package.
|
|
12
69
|
|
|
13
|
-
|
|
14
|
-
page knows who the user is *before* it responds.
|
|
70
|
+
## Quick start
|
|
15
71
|
|
|
16
|
-
|
|
72
|
+
**1. Set the environment variables.**
|
|
17
73
|
|
|
18
74
|
```bash
|
|
19
|
-
npm install @lumoauth/nextjs
|
|
20
|
-
```
|
|
21
|
-
|
|
22
|
-
```
|
|
23
75
|
# .env.local
|
|
24
|
-
NEXT_PUBLIC_LUMOAUTH_DOMAIN=https://app.lumoauth.dev
|
|
76
|
+
NEXT_PUBLIC_LUMOAUTH_DOMAIN=https://app.lumoauth.dev # EU region: https://eu.app.lumoauth.dev
|
|
25
77
|
NEXT_PUBLIC_LUMOAUTH_ORG_ID=acme-corp
|
|
26
78
|
NEXT_PUBLIC_LUMOAUTH_CLIENT_ID=your-client-id
|
|
27
79
|
NEXT_PUBLIC_REDIRECT_URI=http://localhost:3000/api/auth/callback
|
|
28
80
|
|
|
29
|
-
#
|
|
30
|
-
LUMOAUTH_SECRET
|
|
81
|
+
# Encrypts the session cookie. Server only. At least 32 characters: openssl rand -hex 32
|
|
82
|
+
LUMOAUTH_SECRET=replace-with-64-hex-characters
|
|
83
|
+
# Only for a confidential OAuth client. A public client with PKCE leaves it out.
|
|
84
|
+
# LUMOAUTH_CLIENT_SECRET=
|
|
31
85
|
```
|
|
32
86
|
|
|
33
|
-
Mount the
|
|
87
|
+
**2. Mount the route handler.** This one file adds the sign-in, callback, session and sign-out
|
|
88
|
+
routes.
|
|
34
89
|
|
|
35
90
|
```ts
|
|
36
91
|
// app/api/auth/[...lumoauth]/route.ts
|
|
37
92
|
import { createRouteHandler } from '@lumoauth/nextjs/server';
|
|
93
|
+
|
|
38
94
|
export const { GET, POST } = createRouteHandler();
|
|
39
95
|
```
|
|
40
96
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
origin as a post-logout redirect URI so sign-out returns to your app.
|
|
97
|
+
**3. Add the middleware.** It refreshes the access token before each page renders, and it can
|
|
98
|
+
send signed-out visitors to sign-in.
|
|
44
99
|
|
|
45
|
-
|
|
100
|
+
```ts
|
|
101
|
+
// middleware.ts
|
|
102
|
+
import { lumoAuthMiddleware } from '@lumoauth/nextjs/server';
|
|
103
|
+
|
|
104
|
+
export default lumoAuthMiddleware({ protect: ['/dashboard/:path*'] });
|
|
105
|
+
export const config = { matcher: ['/((?!_next|.*\\..*).*)'] };
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
**4. Read the session in a server component.**
|
|
46
109
|
|
|
47
110
|
```tsx
|
|
111
|
+
// app/page.tsx
|
|
48
112
|
import { auth, currentUser } from '@lumoauth/nextjs/server';
|
|
49
113
|
|
|
50
114
|
export default async function Page() {
|
|
51
|
-
const { isSignedIn
|
|
115
|
+
const { isSignedIn } = await auth();
|
|
52
116
|
if (!isSignedIn) return <a href="/api/auth/login">Sign in</a>;
|
|
53
117
|
|
|
54
118
|
const user = await currentUser();
|
|
55
|
-
return
|
|
119
|
+
return (
|
|
120
|
+
<>
|
|
121
|
+
<p>Hello {user?.email}</p>
|
|
122
|
+
<a href="/api/auth/logout">Sign out</a>
|
|
123
|
+
</>
|
|
124
|
+
);
|
|
56
125
|
}
|
|
57
126
|
```
|
|
58
127
|
|
|
59
|
-
|
|
60
|
-
|
|
128
|
+
Sign-in and sign-out are plain links to `/api/auth/login` and `/api/auth/logout`. To send the user
|
|
129
|
+
to a page after sign-in, add `?return_to=/path`.
|
|
130
|
+
|
|
131
|
+
## Core concepts
|
|
132
|
+
|
|
133
|
+
**The server owns the session.** The route handler runs the OAuth 2.0 authorization-code flow
|
|
134
|
+
with PKCE. It stores the tokens in a cookie named `lumo_session`. The cookie is encrypted, so the
|
|
135
|
+
browser cannot read or change it. The refresh token never leaves your server.
|
|
136
|
+
|
|
137
|
+
**The session outlives the access token.** A session lasts 30 days by default. An access token
|
|
138
|
+
lasts about an hour. The middleware replaces the access token when it is about to expire. See
|
|
139
|
+
[Sessions and access tokens](#sessions-and-access-tokens).
|
|
140
|
+
|
|
141
|
+
**Client components share the same session.** `<LumoAuthNextProvider>` reads the access token
|
|
142
|
+
from `/api/auth/session`. Hooks such as `useUser()` and `usePermission()` then return the same user
|
|
143
|
+
that `auth()` returned on the server.
|
|
144
|
+
|
|
145
|
+
**Credentials and scopes** are explained in the
|
|
146
|
+
[client README](../client/README.md#core-concepts). The token from this package is a user access
|
|
147
|
+
token, with the scopes that you set in `scope`.
|
|
148
|
+
|
|
149
|
+
## Configuration
|
|
150
|
+
|
|
151
|
+
Each server function takes an optional config object. Values in that object override the
|
|
152
|
+
environment.
|
|
153
|
+
|
|
154
|
+
| Option | Environment variable | Required | Default | Description |
|
|
155
|
+
|---|---|---|---|---|
|
|
156
|
+
| `domain` | `NEXT_PUBLIC_LUMOAUTH_DOMAIN` | yes | none | Root URL of LumoAuth |
|
|
157
|
+
| `orgId` | `NEXT_PUBLIC_LUMOAUTH_ORG_ID` | yes | none | Organization slug |
|
|
158
|
+
| `clientId` | `NEXT_PUBLIC_LUMOAUTH_CLIENT_ID` | yes | none | OAuth client ID |
|
|
159
|
+
| `redirectUri` | `NEXT_PUBLIC_REDIRECT_URI` | yes | none | Absolute callback URL, registered on the client |
|
|
160
|
+
| `secret` | `LUMOAUTH_SECRET` | yes | none | Encrypts the session cookie. At least 32 characters. |
|
|
161
|
+
| `clientSecret` | `LUMOAUTH_CLIENT_SECRET` | confidential clients only | none | Never give it a `NEXT_PUBLIC_` prefix. |
|
|
162
|
+
| `afterSignInUrl` | none | no | `'/'` | Where a user goes after sign-in when there is no `return_to` |
|
|
163
|
+
| `afterSignOutUrl` | none | no | `'/'` | Where a user goes after sign-out. Also used when sign-in fails. |
|
|
164
|
+
| `scope` | none | no | `'openid profile email'` | OAuth scopes to request. See [Request more scopes](#request-more-scopes). |
|
|
165
|
+
| `sessionMaxAge` | none | no | 30 days | Session lifetime, in seconds |
|
|
166
|
+
|
|
167
|
+
The public values use the `NEXT_PUBLIC_` prefix, so the client provider and the server read the
|
|
168
|
+
same names. The two secrets do not, because Next.js puts every `NEXT_PUBLIC_` value into the
|
|
169
|
+
browser bundle. A missing required value throws an error that names it.
|
|
170
|
+
|
|
171
|
+
Pass the same overrides everywhere when you do not use environment variables:
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
const config = { scope: 'openid profile email authz:read', afterSignInUrl: '/dashboard' };
|
|
175
|
+
export const { GET, POST } = createRouteHandler(config);
|
|
176
|
+
// …and in middleware.ts: lumoAuthMiddleware({ ...config, protect: ['/dashboard/:path*'] })
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## Guides
|
|
180
|
+
|
|
181
|
+
### Read the session in server code
|
|
182
|
+
|
|
183
|
+
`auth()` works in server components, route handlers and server actions. It reads and decrypts
|
|
184
|
+
the cookie, with no network call.
|
|
61
185
|
|
|
62
|
-
|
|
186
|
+
```tsx
|
|
187
|
+
import { auth } from '@lumoauth/nextjs/server';
|
|
188
|
+
|
|
189
|
+
const { isSignedIn, userId, getToken, expiresAt, isStale } = await auth();
|
|
190
|
+
```
|
|
63
191
|
|
|
64
|
-
|
|
192
|
+
| Field | Meaning |
|
|
193
|
+
|---|---|
|
|
194
|
+
| `isSignedIn` | The user has a live **session**. This stays `true` when only the access token has expired. |
|
|
195
|
+
| `userId` | The user's OIDC subject (`sub`), or `null` |
|
|
196
|
+
| `getToken()` | The access token, or `null` when it has expired and nothing refreshed it |
|
|
197
|
+
| `expiresAt` | When the access token expires, in epoch milliseconds |
|
|
198
|
+
| `isStale` | `true` when the session is live but the access token has expired. This happens only on routes without the middleware. |
|
|
199
|
+
|
|
200
|
+
`currentUser()` returns the user's profile from the OIDC UserInfo endpoint, or `null`. It makes a
|
|
201
|
+
network call each time, so use `auth()` when the subject is enough. A failed UserInfo call
|
|
202
|
+
returns `null` and leaves the session alone.
|
|
203
|
+
|
|
204
|
+
### Protect pages
|
|
205
|
+
|
|
206
|
+
Choose one of two ways, or use both.
|
|
207
|
+
|
|
208
|
+
**In the middleware.** Matching paths redirect signed-out visitors to
|
|
209
|
+
`/api/auth/login?return_to=<path>`.
|
|
65
210
|
|
|
66
211
|
```ts
|
|
67
|
-
|
|
68
|
-
|
|
212
|
+
export default lumoAuthMiddleware({
|
|
213
|
+
protect: ['/dashboard/:path*', /^\/settings/], // globs, regular expressions, or a function
|
|
214
|
+
});
|
|
215
|
+
```
|
|
69
216
|
|
|
70
|
-
|
|
71
|
-
|
|
217
|
+
**In the page.** `protectPage()` redirects a signed-out visitor to sign-in. Otherwise it returns
|
|
218
|
+
the same object as `auth()`.
|
|
219
|
+
|
|
220
|
+
```tsx
|
|
221
|
+
import { protectPage } from '@lumoauth/nextjs/server';
|
|
222
|
+
|
|
223
|
+
export default async function Dashboard() {
|
|
224
|
+
const { userId } = await protectPage({ returnTo: '/dashboard' });
|
|
225
|
+
return <p>Signed in as {userId}</p>;
|
|
226
|
+
}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
These checks only confirm that a valid session cookie exists. They do not protect your data on
|
|
230
|
+
their own. Your API must still check the token and the user's permissions.
|
|
231
|
+
|
|
232
|
+
### Call LumoAuth or your API with the user's token
|
|
233
|
+
|
|
234
|
+
`getToken()` returns the user's access token in server code. Use it with
|
|
235
|
+
[`@lumoauth/client`](../client/README.md) to run checks as that user:
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
// app/api/documents/[id]/route.ts
|
|
239
|
+
import { auth } from '@lumoauth/nextjs/server';
|
|
240
|
+
import { LumoAuth } from '@lumoauth/client';
|
|
241
|
+
|
|
242
|
+
export async function DELETE(req: Request) {
|
|
243
|
+
const token = (await auth()).getToken();
|
|
244
|
+
if (!token) return new Response('Unauthorized', { status: 401 });
|
|
245
|
+
|
|
246
|
+
const lumo = new LumoAuth({
|
|
247
|
+
baseUrl: process.env.NEXT_PUBLIC_LUMOAUTH_DOMAIN!,
|
|
248
|
+
orgId: process.env.NEXT_PUBLIC_LUMOAUTH_ORG_ID!,
|
|
249
|
+
token,
|
|
250
|
+
});
|
|
251
|
+
if (!(await lumo.permissions.check('document.delete'))) {
|
|
252
|
+
return new Response('Forbidden', { status: 403 });
|
|
253
|
+
}
|
|
254
|
+
// …delete the document
|
|
255
|
+
return new Response(null, { status: 204 });
|
|
256
|
+
}
|
|
72
257
|
```
|
|
73
258
|
|
|
74
|
-
|
|
75
|
-
|
|
259
|
+
Middleware does not run on API routes unless your `matcher` includes them. If it does not,
|
|
260
|
+
`getToken()` can return `null` on an API route after the token expires. The example `matcher`
|
|
261
|
+
above covers API routes.
|
|
76
262
|
|
|
77
|
-
|
|
263
|
+
### Use components and hooks in client components
|
|
264
|
+
|
|
265
|
+
Wrap the app in `<LumoAuthNextProvider>`. It takes the same props as `<LumoAuthProvider>` from
|
|
266
|
+
`@lumoauth/react`, except `storage`, plus `basePath`.
|
|
78
267
|
|
|
79
268
|
```tsx
|
|
269
|
+
// app/providers.tsx
|
|
80
270
|
'use client';
|
|
81
|
-
import { LumoAuthNextProvider
|
|
271
|
+
import { LumoAuthNextProvider } from '@lumoauth/nextjs';
|
|
272
|
+
|
|
273
|
+
export function Providers({ children }: { children: React.ReactNode }) {
|
|
274
|
+
return (
|
|
275
|
+
<LumoAuthNextProvider
|
|
276
|
+
domain={process.env.NEXT_PUBLIC_LUMOAUTH_DOMAIN!}
|
|
277
|
+
orgId={process.env.NEXT_PUBLIC_LUMOAUTH_ORG_ID!}
|
|
278
|
+
clientId={process.env.NEXT_PUBLIC_LUMOAUTH_CLIENT_ID!}
|
|
279
|
+
>
|
|
280
|
+
{children}
|
|
281
|
+
</LumoAuthNextProvider>
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
```tsx
|
|
287
|
+
// app/layout.tsx
|
|
288
|
+
import { Providers } from './providers';
|
|
289
|
+
|
|
290
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
291
|
+
return (
|
|
292
|
+
<html lang="en">
|
|
293
|
+
<body><Providers>{children}</Providers></body>
|
|
294
|
+
</html>
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
```tsx
|
|
300
|
+
// any client component
|
|
301
|
+
'use client';
|
|
302
|
+
import { useUser, UserAvatar, Protect } from '@lumoauth/nextjs';
|
|
303
|
+
|
|
304
|
+
export function Header() {
|
|
305
|
+
const user = useUser();
|
|
306
|
+
if (!user) return <a href="/api/auth/login">Sign in</a>;
|
|
307
|
+
return (
|
|
308
|
+
<>
|
|
309
|
+
<UserAvatar /> {user.displayName}
|
|
310
|
+
<Protect permission="admin.dashboard"><a href="/admin">Admin</a></Protect>
|
|
311
|
+
<a href="/api/auth/logout">Sign out</a>
|
|
312
|
+
</>
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
| Prop | Default | Description |
|
|
318
|
+
|---|---|---|
|
|
319
|
+
| `basePath` | `'/api/auth'` | Where you mounted the route handler. The provider reads `<basePath>/session` and calls `<basePath>/logout`. |
|
|
320
|
+
| `domain`, `orgId`, `clientId`, … | | As for `<LumoAuthProvider>`; see the [React README](../react/README.md#configuration) |
|
|
321
|
+
|
|
322
|
+
Start sign-in and sign-out with links to `/api/auth/login` and `/api/auth/logout`. Do not use
|
|
323
|
+
`signIn()`, `<SignIn>`, `<SignInButton>` or `<RedirectToSignIn>` with this provider. Those start
|
|
324
|
+
a sign-in in the browser, and the cookie storage cannot save tokens that the browser receives.
|
|
325
|
+
|
|
326
|
+
### Request more scopes
|
|
327
|
+
|
|
328
|
+
Some LumoAuth calls need a scope on the user's token. For example, listing the user's
|
|
329
|
+
permissions needs `authz:read`, and ABAC checks need `abac:read`. Add the scopes to `scope`, and
|
|
330
|
+
allow them on the OAuth client:
|
|
331
|
+
|
|
332
|
+
```ts
|
|
333
|
+
export const { GET, POST } = createRouteHandler({
|
|
334
|
+
scope: 'openid profile email authz:read abac:read',
|
|
335
|
+
});
|
|
82
336
|
```
|
|
83
337
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
re-exported.
|
|
338
|
+
The new scopes apply after the user signs in again. The full table is in the
|
|
339
|
+
[client README](../client/README.md#scopes).
|
|
87
340
|
|
|
88
341
|
## How the session is protected
|
|
89
342
|
|
|
90
|
-
The cookie is encrypted
|
|
91
|
-
`LUMOAUTH_SECRET
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
343
|
+
The cookie is encrypted and authenticated with AES-256-GCM, using a key derived from
|
|
344
|
+
`LUMOAUTH_SECRET`. The browser can neither read nor change it. A changed cookie fails the check
|
|
345
|
+
and counts as no session.
|
|
346
|
+
|
|
347
|
+
The cookie is encrypted, not only signed, because it holds the refresh token. The
|
|
348
|
+
`/api/auth/session` route returns the access token, the ID token and the expiry time to the
|
|
349
|
+
client provider. It never returns the refresh token.
|
|
95
350
|
|
|
96
|
-
`auth()` does not
|
|
97
|
-
|
|
98
|
-
there after a successful exchange, and the cookie is unforgeable.
|
|
351
|
+
`auth()` does not check the access token's signature against LumoAuth's keys. The token can only
|
|
352
|
+
be in the cookie because this package stored it there after a successful code exchange.
|
|
99
353
|
|
|
100
|
-
|
|
354
|
+
The sign-in step stores the PKCE verifier, the `state` and the `return_to` path in a second
|
|
355
|
+
encrypted cookie, `lumo_pkce`, for 10 minutes. `return_to` accepts only paths on your own site.
|
|
101
356
|
|
|
102
|
-
|
|
103
|
-
to log everybody out every hour.
|
|
357
|
+
## Sessions and access tokens
|
|
104
358
|
|
|
105
359
|
| | Lifetime | Meaning |
|
|
106
360
|
|---|---|---|
|
|
107
|
-
|
|
|
108
|
-
|
|
|
361
|
+
| Session | `sessionMaxAge`, 30 days by default | The user is signed in. |
|
|
362
|
+
| Access token | about an hour, set by LumoAuth | A credential for calling APIs |
|
|
109
363
|
|
|
110
|
-
`auth().isSignedIn`
|
|
111
|
-
|
|
364
|
+
`auth().isSignedIn` describes the session. A user whose access token expired a minute ago is
|
|
365
|
+
still signed in, and the token only needs replacing.
|
|
112
366
|
|
|
113
|
-
|
|
114
|
-
|
|
367
|
+
The middleware replaces it. When the access token expires within 60 seconds, the middleware
|
|
368
|
+
uses the refresh token to get a new one. It stores the result in the cookie before the page
|
|
369
|
+
renders. Install it even when you protect no paths:
|
|
115
370
|
|
|
116
371
|
```ts
|
|
117
|
-
export default lumoAuthMiddleware(); // refresh only
|
|
372
|
+
export default lumoAuthMiddleware(); // refresh only
|
|
118
373
|
```
|
|
119
374
|
|
|
120
|
-
|
|
375
|
+
The refresh must happen in middleware for two reasons:
|
|
121
376
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
377
|
+
- In Next.js, only middleware, route handlers and server actions can write cookies. A server
|
|
378
|
+
component cannot store a new token.
|
|
379
|
+
- LumoAuth rotates refresh tokens. Each refresh returns a new refresh token, and the old one stops
|
|
380
|
+
working. A refresh whose result is not saved would break the session on the next request.
|
|
125
381
|
|
|
126
|
-
|
|
127
|
-
and revokes the old one on use**, so refreshing somewhere that cannot save the
|
|
128
|
-
result would spend the token and break the session on the very next request.
|
|
129
|
-
`auth()` therefore returns `getToken() === null` and `isStale === true` rather
|
|
130
|
-
than performing a refresh it cannot persist.
|
|
382
|
+
So `auth()` never refreshes. It returns `getToken() === null` and `isStale === true` instead.
|
|
131
383
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
384
|
+
The middleware writes the new cookie on the response, but the page reads the request. So the
|
|
385
|
+
middleware also forwards the new session in a request header (`x-lumo-session`), which `auth()`
|
|
386
|
+
reads first. The new token is therefore available on the same request.
|
|
387
|
+
|
|
388
|
+
## API reference
|
|
389
|
+
|
|
390
|
+
**`@lumoauth/nextjs/server`** (marked `server-only`; importing it from a client component fails
|
|
391
|
+
the build)
|
|
392
|
+
|
|
393
|
+
| Export | Description |
|
|
394
|
+
|---|---|
|
|
395
|
+
| `auth(config?)` | Returns `{ userId, isSignedIn, getToken, expiresAt, isStale }` from the cookie |
|
|
396
|
+
| `currentUser(config?)` | Returns the UserInfo profile, or `null` |
|
|
397
|
+
| `protectPage({ returnTo? })` | Redirects to sign-in without a session; otherwise returns `auth()` |
|
|
398
|
+
| `createRouteHandler(config?)` | Returns `{ GET, POST }` for `app/api/auth/[...lumoauth]/route.ts` |
|
|
399
|
+
| `lumoAuthMiddleware(options?)` | Refresh and route protection. Options: `protect` (globs such as `/dashboard/:path*`, regular expressions, or a function of the request) and `refresh` (default `true`), plus any config value. |
|
|
400
|
+
| `resolveConfig(overrides?)` | Merges overrides with the environment and checks the required values |
|
|
401
|
+
| `SESSION_COOKIE` | `'lumo_session'` |
|
|
402
|
+
| `REFRESHED_SESSION_HEADER` | `'x-lumo-session'` |
|
|
403
|
+
| `isSessionLive(session)`, `isTokenStale(session)` | Helpers for custom integrations |
|
|
404
|
+
| Types | `AuthObject`, `MiddlewareOptions`, `LumoAuthNextConfig`, `ServerSession` |
|
|
405
|
+
|
|
406
|
+
**Routes from `createRouteHandler()`** (shown with the default mount point)
|
|
407
|
+
|
|
408
|
+
| Route | Method | What it does |
|
|
409
|
+
|---|---|---|
|
|
410
|
+
| `/api/auth/login` | GET | Starts sign-in and redirects to LumoAuth. Accepts `?return_to=/path`. |
|
|
411
|
+
| `/api/auth/callback` | GET | Checks `state`, exchanges the code, stores the session, and redirects to `return_to` |
|
|
412
|
+
| `/api/auth/session` | GET | Returns `{ accessToken, idToken, expiresAt }` for the client provider. Returns `null` values without a session. |
|
|
413
|
+
| `/api/auth/logout` | GET, POST | Revokes the access token, clears the cookie, and ends the LumoAuth session through its logout endpoint. LumoAuth then redirects to `afterSignOutUrl`. |
|
|
136
414
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
415
|
+
**`@lumoauth/nextjs`** (client)
|
|
416
|
+
|
|
417
|
+
| Export | Description |
|
|
418
|
+
|---|---|
|
|
419
|
+
| `LumoAuthNextProvider` | `<LumoAuthProvider>` that reads the session from the route handler |
|
|
420
|
+
| Components and hooks | Everything from [`@lumoauth/react`](../react/README.md#api-reference) |
|
|
421
|
+
| `LumoAuth` | The browser client from `@lumoauth/client` |
|
|
422
|
+
|
|
423
|
+
## Troubleshooting
|
|
424
|
+
|
|
425
|
+
| Symptom | Cause | Fix |
|
|
426
|
+
|---|---|---|
|
|
427
|
+
| `@lumoauth/nextjs is missing required config: …` | A required environment variable is not set. | Set the variables named in the message, or pass them as config. |
|
|
428
|
+
| `LUMOAUTH_SECRET must be set to at least 32 characters` | The secret is missing or too short. | Generate one with `openssl rand -hex 32`. |
|
|
429
|
+
| `getToken()` returns `null` while `isSignedIn` is `true` | The access token expired and no middleware ran on this route. | Install `lumoAuthMiddleware()` and make sure its `matcher` covers the route. |
|
|
430
|
+
| After sign-in the user lands on `afterSignOutUrl` | The callback failed. The `state` did not match, the PKCE cookie expired after 10 minutes, or the code exchange failed. | Start sign-in again. Check that the redirect URI and the client secret are correct. |
|
|
431
|
+
| After sign-out the user is still signed in at LumoAuth | `<origin><afterSignOutUrl>` is not a registered post-logout redirect URI. | Register it on the OAuth client. |
|
|
432
|
+
| A `403` with `requiredScopes`, such as `['authz:read']` | The token lacks a scope. | Add the scope to `scope` and sign in again. |
|
|
433
|
+
| Hooks show the user as signed out after `<SignInButton>` | A browser sign-in cannot save tokens into the cookie session. | Link to `/api/auth/login` instead. |
|
|
434
|
+
| The cookie stops working after you change `LUMOAUTH_SECRET` | The old cookie cannot be decrypted. | This is expected. The middleware clears the cookie and the user signs in again. |
|
|
141
435
|
|
|
142
436
|
## Limitations
|
|
143
437
|
|
|
144
|
-
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
438
|
+
- Only the App Router is supported. The Pages Router is not supported yet.
|
|
439
|
+
- Without the middleware, `getToken()` returns `null` after the access token expires. The session
|
|
440
|
+
stays valid, but you get no token until a refresh runs.
|
|
441
|
+
|
|
442
|
+
## Versioning and compatibility
|
|
443
|
+
|
|
444
|
+
This package is version 1.0.0. It needs LumoAuth server API 1.0.0 or newer, Next.js 14 or newer,
|
|
445
|
+
and React 18 or newer.
|
|
446
|
+
|
|
447
|
+
## Related packages
|
|
448
|
+
|
|
449
|
+
| Package | Relationship |
|
|
450
|
+
|---|---|
|
|
451
|
+
| [`@lumoauth/react`](../react/README.md) | The components and hooks that this package re-exports |
|
|
452
|
+
| [`@lumoauth/client`](../client/README.md) | The client underneath, including `cookieStorageAdapter` |
|
|
453
|
+
| [`@lumoauth/backend`](../backend/README.md) | For API routes that use your organization's credential instead of the user's token |
|
|
454
|
+
| [`@lumoauth/express`](../express/README.md) | Sign-in routes for Express |
|
|
455
|
+
| [Workspace README](../../README.md) | How the packages fit together |
|
|
456
|
+
|
|
457
|
+
More: [Next.js quickstart](https://docs.lumoauth.dev/quickstarts/nextjs/),
|
|
458
|
+
[SDK overview](https://docs.lumoauth.dev/developer/sdks/), and the
|
|
459
|
+
[example app](../../examples/nextjs/README.md), which has server-rendered `/ssr` pages.
|
|
460
|
+
|
|
461
|
+
## Licence
|
|
462
|
+
|
|
463
|
+
[MIT](./LICENSE)
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lumoauth/nextjs",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "LumoAuth for Next.js
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "LumoAuth for Next.js — server-side auth() for App Router, route protection middleware, and a backend-for-frontend that keeps tokens out of the browser.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "LumoAuth",
|
|
7
7
|
"publishConfig": {
|