@lumoauth/nextjs 0.0.0-stage → 1.1.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/LICENSE +21 -0
- package/README.md +462 -2
- package/dist/index.d.mts +19 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +110 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +72 -0
- package/dist/index.mjs.map +1 -0
- package/dist/server.d.mts +232 -0
- package/dist/server.d.ts +232 -0
- package/dist/server.js +433 -0
- package/dist/server.js.map +1 -0
- package/dist/server.mjs +396 -0
- package/dist/server.mjs.map +1 -0
- package/package.json +67 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 LumoAuth LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,463 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lumoauth/nextjs
|
|
2
2
|
|
|
3
|
-
|
|
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
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
npm install @lumoauth/nextjs
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`next` and `react` are peer dependencies. `@lumoauth/react` and `@lumoauth/client` are installed
|
|
68
|
+
with this package.
|
|
69
|
+
|
|
70
|
+
## Quick start
|
|
71
|
+
|
|
72
|
+
**1. Set the environment variables.**
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
# .env.local
|
|
76
|
+
NEXT_PUBLIC_LUMOAUTH_DOMAIN=https://app.lumoauth.dev # EU region: https://eu.app.lumoauth.dev
|
|
77
|
+
NEXT_PUBLIC_LUMOAUTH_ORG_ID=acme-corp
|
|
78
|
+
NEXT_PUBLIC_LUMOAUTH_CLIENT_ID=your-client-id
|
|
79
|
+
NEXT_PUBLIC_REDIRECT_URI=http://localhost:3000/api/auth/callback
|
|
80
|
+
|
|
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=
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
**2. Mount the route handler.** This one file adds the sign-in, callback, session and sign-out
|
|
88
|
+
routes.
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
// app/api/auth/[...lumoauth]/route.ts
|
|
92
|
+
import { createRouteHandler } from '@lumoauth/nextjs/server';
|
|
93
|
+
|
|
94
|
+
export const { GET, POST } = createRouteHandler();
|
|
95
|
+
```
|
|
96
|
+
|
|
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.
|
|
99
|
+
|
|
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.**
|
|
109
|
+
|
|
110
|
+
```tsx
|
|
111
|
+
// app/page.tsx
|
|
112
|
+
import { auth, currentUser } from '@lumoauth/nextjs/server';
|
|
113
|
+
|
|
114
|
+
export default async function Page() {
|
|
115
|
+
const { isSignedIn } = await auth();
|
|
116
|
+
if (!isSignedIn) return <a href="/api/auth/login">Sign in</a>;
|
|
117
|
+
|
|
118
|
+
const user = await currentUser();
|
|
119
|
+
return (
|
|
120
|
+
<>
|
|
121
|
+
<p>Hello {user?.email}</p>
|
|
122
|
+
<a href="/api/auth/logout">Sign out</a>
|
|
123
|
+
</>
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
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.
|
|
185
|
+
|
|
186
|
+
```tsx
|
|
187
|
+
import { auth } from '@lumoauth/nextjs/server';
|
|
188
|
+
|
|
189
|
+
const { isSignedIn, userId, getToken, expiresAt, isStale } = await auth();
|
|
190
|
+
```
|
|
191
|
+
|
|
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>`.
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
export default lumoAuthMiddleware({
|
|
213
|
+
protect: ['/dashboard/:path*', /^\/settings/], // globs, regular expressions, or a function
|
|
214
|
+
});
|
|
215
|
+
```
|
|
216
|
+
|
|
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
|
+
}
|
|
257
|
+
```
|
|
258
|
+
|
|
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.
|
|
262
|
+
|
|
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`.
|
|
267
|
+
|
|
268
|
+
```tsx
|
|
269
|
+
// app/providers.tsx
|
|
270
|
+
'use client';
|
|
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
|
+
});
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
The new scopes apply after the user signs in again. The full table is in the
|
|
339
|
+
[client README](../client/README.md#scopes).
|
|
340
|
+
|
|
341
|
+
## How the session is protected
|
|
342
|
+
|
|
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.
|
|
350
|
+
|
|
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.
|
|
353
|
+
|
|
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.
|
|
356
|
+
|
|
357
|
+
## Sessions and access tokens
|
|
358
|
+
|
|
359
|
+
| | Lifetime | Meaning |
|
|
360
|
+
|---|---|---|
|
|
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 |
|
|
363
|
+
|
|
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.
|
|
366
|
+
|
|
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:
|
|
370
|
+
|
|
371
|
+
```ts
|
|
372
|
+
export default lumoAuthMiddleware(); // refresh only
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
The refresh must happen in middleware for two reasons:
|
|
376
|
+
|
|
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.
|
|
381
|
+
|
|
382
|
+
So `auth()` never refreshes. It returns `getToken() === null` and `isStale === true` instead.
|
|
383
|
+
|
|
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`. |
|
|
414
|
+
|
|
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. |
|
|
435
|
+
|
|
436
|
+
## Limitations
|
|
437
|
+
|
|
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/dist/index.d.mts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { LumoAuthProviderProps } from '@lumoauth/react';
|
|
2
|
+
export { AppearanceProps, AuthCallback, AuthCallbackProps, AuthState, AuthStatus, LumoAuth, LumoAuthConfig, LumoAuthContextValue, LumoAuthProvider, LumoAuthProviderProps, LumoAuthUser, Protect, ProtectProps, RedirectToSignIn, RedirectToSignInProps, SignIn, SignInButton, SignInButtonProps, SignInProps, SignOutButton, SignOutButtonProps, SignUp, SignUpButton, SignUpButtonProps, SignUpProps, SignedIn, SignedInProps, SignedOut, SignedOutProps, UseEmailFirstReturn, UseMagicLinkReturn, UserAvatar, UserAvatarProps, UserButton, UserButtonProps, UserProfile, UserProfileProps, useAbac, useAuth, useEmailFirst, useLumoAuth, useMagicLink, usePermission, useSession, useSignIn, useUser, useZanzibar } from '@lumoauth/react';
|
|
3
|
+
import * as react from 'react';
|
|
4
|
+
|
|
5
|
+
type LumoAuthNextProviderProps = Omit<LumoAuthProviderProps, 'storage'> & {
|
|
6
|
+
/** Base path where createRouteHandler is mounted. @default '/api/auth' */
|
|
7
|
+
basePath?: string;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Provider wired to the server-side session.
|
|
11
|
+
*
|
|
12
|
+
* The plain `<LumoAuthProvider>` keeps tokens in web storage, which the server
|
|
13
|
+
* cannot see — so a page always renders signed-out first and corrects itself
|
|
14
|
+
* after hydration. This one reads the session from the httpOnly cookie via the
|
|
15
|
+
* route handler, matching what `auth()` already rendered on the server.
|
|
16
|
+
*/
|
|
17
|
+
declare function LumoAuthNextProvider({ basePath, children, ...rest }: LumoAuthNextProviderProps): react.JSX.Element;
|
|
18
|
+
|
|
19
|
+
export { LumoAuthNextProvider };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { LumoAuthProviderProps } from '@lumoauth/react';
|
|
2
|
+
export { AppearanceProps, AuthCallback, AuthCallbackProps, AuthState, AuthStatus, LumoAuth, LumoAuthConfig, LumoAuthContextValue, LumoAuthProvider, LumoAuthProviderProps, LumoAuthUser, Protect, ProtectProps, RedirectToSignIn, RedirectToSignInProps, SignIn, SignInButton, SignInButtonProps, SignInProps, SignOutButton, SignOutButtonProps, SignUp, SignUpButton, SignUpButtonProps, SignUpProps, SignedIn, SignedInProps, SignedOut, SignedOutProps, UseEmailFirstReturn, UseMagicLinkReturn, UserAvatar, UserAvatarProps, UserButton, UserButtonProps, UserProfile, UserProfileProps, useAbac, useAuth, useEmailFirst, useLumoAuth, useMagicLink, usePermission, useSession, useSignIn, useUser, useZanzibar } from '@lumoauth/react';
|
|
3
|
+
import * as react from 'react';
|
|
4
|
+
|
|
5
|
+
type LumoAuthNextProviderProps = Omit<LumoAuthProviderProps, 'storage'> & {
|
|
6
|
+
/** Base path where createRouteHandler is mounted. @default '/api/auth' */
|
|
7
|
+
basePath?: string;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Provider wired to the server-side session.
|
|
11
|
+
*
|
|
12
|
+
* The plain `<LumoAuthProvider>` keeps tokens in web storage, which the server
|
|
13
|
+
* cannot see — so a page always renders signed-out first and corrects itself
|
|
14
|
+
* after hydration. This one reads the session from the httpOnly cookie via the
|
|
15
|
+
* route handler, matching what `auth()` already rendered on the server.
|
|
16
|
+
*/
|
|
17
|
+
declare function LumoAuthNextProvider({ basePath, children, ...rest }: LumoAuthNextProviderProps): react.JSX.Element;
|
|
18
|
+
|
|
19
|
+
export { LumoAuthNextProvider };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
"use strict";
|
|
3
|
+
"use client";
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
21
|
+
|
|
22
|
+
// src/index.ts
|
|
23
|
+
var src_exports = {};
|
|
24
|
+
__export(src_exports, {
|
|
25
|
+
AuthCallback: () => import_react5.AuthCallback,
|
|
26
|
+
LumoAuth: () => import_react3.LumoAuth,
|
|
27
|
+
LumoAuthNextProvider: () => LumoAuthNextProvider,
|
|
28
|
+
LumoAuthProvider: () => import_react4.LumoAuthProvider,
|
|
29
|
+
Protect: () => import_react7.Protect,
|
|
30
|
+
RedirectToSignIn: () => import_react8.RedirectToSignIn,
|
|
31
|
+
SignIn: () => import_react5.SignIn,
|
|
32
|
+
SignInButton: () => import_react9.SignInButton,
|
|
33
|
+
SignOutButton: () => import_react9.SignOutButton,
|
|
34
|
+
SignUp: () => import_react5.SignUp,
|
|
35
|
+
SignUpButton: () => import_react9.SignUpButton,
|
|
36
|
+
SignedIn: () => import_react8.SignedIn,
|
|
37
|
+
SignedOut: () => import_react8.SignedOut,
|
|
38
|
+
UserAvatar: () => import_react6.UserAvatar,
|
|
39
|
+
UserButton: () => import_react6.UserButton,
|
|
40
|
+
UserProfile: () => import_react6.UserProfile,
|
|
41
|
+
useAbac: () => import_react10.useAbac,
|
|
42
|
+
useAuth: () => import_react10.useAuth,
|
|
43
|
+
useEmailFirst: () => import_react10.useEmailFirst,
|
|
44
|
+
useLumoAuth: () => import_react10.useLumoAuth,
|
|
45
|
+
useMagicLink: () => import_react10.useMagicLink,
|
|
46
|
+
usePermission: () => import_react10.usePermission,
|
|
47
|
+
useSession: () => import_react10.useSession,
|
|
48
|
+
useSignIn: () => import_react10.useSignIn,
|
|
49
|
+
useUser: () => import_react10.useUser,
|
|
50
|
+
useZanzibar: () => import_react10.useZanzibar
|
|
51
|
+
});
|
|
52
|
+
module.exports = __toCommonJS(src_exports);
|
|
53
|
+
var import_react3 = require("@lumoauth/react");
|
|
54
|
+
var import_react4 = require("@lumoauth/react");
|
|
55
|
+
var import_react5 = require("@lumoauth/react");
|
|
56
|
+
var import_react6 = require("@lumoauth/react");
|
|
57
|
+
var import_react7 = require("@lumoauth/react");
|
|
58
|
+
var import_react8 = require("@lumoauth/react");
|
|
59
|
+
var import_react9 = require("@lumoauth/react");
|
|
60
|
+
var import_react10 = require("@lumoauth/react");
|
|
61
|
+
|
|
62
|
+
// src/provider.tsx
|
|
63
|
+
var import_react = require("react");
|
|
64
|
+
var import_react2 = require("@lumoauth/react");
|
|
65
|
+
var import_client = require("@lumoauth/client");
|
|
66
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
67
|
+
function LumoAuthNextProvider({
|
|
68
|
+
basePath = "/api/auth",
|
|
69
|
+
children,
|
|
70
|
+
...rest
|
|
71
|
+
}) {
|
|
72
|
+
const storage = (0, import_react.useMemo)(
|
|
73
|
+
() => (0, import_client.cookieStorageAdapter)({
|
|
74
|
+
sessionEndpoint: `${basePath}/session`,
|
|
75
|
+
logoutEndpoint: `${basePath}/logout`
|
|
76
|
+
}),
|
|
77
|
+
[basePath]
|
|
78
|
+
);
|
|
79
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react2.LumoAuthProvider, { ...rest, storage, children });
|
|
80
|
+
}
|
|
81
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
82
|
+
0 && (module.exports = {
|
|
83
|
+
AuthCallback,
|
|
84
|
+
LumoAuth,
|
|
85
|
+
LumoAuthNextProvider,
|
|
86
|
+
LumoAuthProvider,
|
|
87
|
+
Protect,
|
|
88
|
+
RedirectToSignIn,
|
|
89
|
+
SignIn,
|
|
90
|
+
SignInButton,
|
|
91
|
+
SignOutButton,
|
|
92
|
+
SignUp,
|
|
93
|
+
SignUpButton,
|
|
94
|
+
SignedIn,
|
|
95
|
+
SignedOut,
|
|
96
|
+
UserAvatar,
|
|
97
|
+
UserButton,
|
|
98
|
+
UserProfile,
|
|
99
|
+
useAbac,
|
|
100
|
+
useAuth,
|
|
101
|
+
useEmailFirst,
|
|
102
|
+
useLumoAuth,
|
|
103
|
+
useMagicLink,
|
|
104
|
+
usePermission,
|
|
105
|
+
useSession,
|
|
106
|
+
useSignIn,
|
|
107
|
+
useUser,
|
|
108
|
+
useZanzibar
|
|
109
|
+
});
|
|
110
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/provider.tsx"],"sourcesContent":["'use client';\n\n// @lumoauth/nextjs — client entry.\n//\n// Re-exports the React SDK so a Next.js app needs one dependency. Everything\n// server-side (auth, currentUser, route handlers, middleware) lives in\n// @lumoauth/nextjs/server, which is never bundled for the browser.\n\n// Named re-exports, not `export *`: Next 14 rejects `export *` in a module\n// carrying the \"use client\" directive. Keep this list in sync with\n// @lumoauth/react's index.\nexport { LumoAuth, type LumoAuthConfig } from '@lumoauth/react';\n\n// Provider\nexport { LumoAuthProvider } from '@lumoauth/react';\n\n// Authentication Components\nexport { SignIn, SignUp, AuthCallback } from '@lumoauth/react';\n\n// User Components\nexport { UserButton, UserAvatar, UserProfile } from '@lumoauth/react';\n\n// Authorization Components\nexport { Protect } from '@lumoauth/react';\n\n// Control Components\nexport { SignedIn, SignedOut, RedirectToSignIn } from '@lumoauth/react';\n\n// Unstyled Components\nexport { SignInButton, SignUpButton, SignOutButton } from '@lumoauth/react';\n\n// Hooks\nexport {\n useAuth,\n useUser,\n useSignIn,\n useSession,\n useLumoAuth,\n usePermission,\n useZanzibar,\n useAbac,\n useMagicLink,\n useEmailFirst,\n} from '@lumoauth/react';\n\n// Types\nexport type {\n LumoAuthProviderProps,\n LumoAuthUser,\n AuthState,\n AuthStatus,\n LumoAuthContextValue,\n SignInProps,\n SignUpProps,\n UserButtonProps,\n UserAvatarProps,\n UserProfileProps,\n ProtectProps,\n AppearanceProps,\n AuthCallbackProps,\n SignedInProps,\n SignedOutProps,\n SignInButtonProps,\n SignUpButtonProps,\n SignOutButtonProps,\n RedirectToSignInProps,\n UseMagicLinkReturn,\n UseEmailFirstReturn,\n} from '@lumoauth/react';\n\nexport { LumoAuthNextProvider } from './provider';\n","'use client';\n\nimport { useMemo } from 'react';\nimport { LumoAuthProvider, type LumoAuthProviderProps } from '@lumoauth/react';\nimport { cookieStorageAdapter } from '@lumoauth/client';\n\nexport type LumoAuthNextProviderProps = Omit<LumoAuthProviderProps, 'storage'> & {\n /** Base path where createRouteHandler is mounted. @default '/api/auth' */\n basePath?: string;\n};\n\n/**\n * Provider wired to the server-side session.\n *\n * The plain `<LumoAuthProvider>` keeps tokens in web storage, which the server\n * cannot see — so a page always renders signed-out first and corrects itself\n * after hydration. This one reads the session from the httpOnly cookie via the\n * route handler, matching what `auth()` already rendered on the server.\n */\nexport function LumoAuthNextProvider({\n basePath = '/api/auth',\n children,\n ...rest\n}: LumoAuthNextProviderProps) {\n // Memoised: `storage` is a dependency of the provider's session useMemo, so\n // a new adapter each render would rebuild the session every render.\n const storage = useMemo(\n () =>\n cookieStorageAdapter({\n sessionEndpoint: `${basePath}/session`,\n logoutEndpoint: `${basePath}/logout`,\n }),\n [basePath],\n );\n\n return (\n <LumoAuthProvider {...rest} storage={storage}>\n {children}\n </LumoAuthProvider>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,IAAAA,gBAA8C;AAG9C,IAAAA,gBAAiC;AAGjC,IAAAA,gBAA6C;AAG7C,IAAAA,gBAAoD;AAGpD,IAAAA,gBAAwB;AAGxB,IAAAA,gBAAsD;AAGtD,IAAAA,gBAA0D;AAG1D,IAAAA,iBAWO;;;ACzCP,mBAAwB;AACxB,IAAAC,gBAA6D;AAC7D,oBAAqC;AAgC7B;AAjBD,SAAS,qBAAqB;AAAA,EACjC,WAAW;AAAA,EACX;AAAA,EACA,GAAG;AACP,GAA8B;AAG1B,QAAM,cAAU;AAAA,IACZ,UACI,oCAAqB;AAAA,MACjB,iBAAiB,GAAG,QAAQ;AAAA,MAC5B,gBAAgB,GAAG,QAAQ;AAAA,IAC/B,CAAC;AAAA,IACL,CAAC,QAAQ;AAAA,EACb;AAEA,SACI,4CAAC,kCAAkB,GAAG,MAAM,SACvB,UACL;AAER;","names":["import_react","import_react"]}
|