@propelauth/nextjs 0.3.6 → 0.3.8

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 CHANGED
@@ -31,30 +31,31 @@ When you copy the PROPELAUTH_VERIFIER_KEY from the PropelAuth dashboard, it will
31
31
  PROPELAUTH_VERIFIER_KEY=-----BEGIN PUBLIC KEY-----\nMIIBIjANBgk...
32
32
  ```
33
33
 
34
+ If authentication URL needs to be set at runtime, use `PROPELAUTH_AUTH_URL`. Otherwise, it falls back to `NEXT_PUBLIC_AUTH_URL`, which is set at build time.
34
35
 
35
- For the PROPELAUTH_REDIRECT_URI variable, you need to add /api/auth/callback to the end of one of your allowed frontend locations. So, for example, if you are developing in the test environment and using http://localhost:3000, you would use http://localhost:3000/api/auth/callback
36
+ For the PROPELAUTH_REDIRECT_URI variable, you need to add /api/auth/callback to the end of one of your allowed frontend locations. So, for example, if you are developing in the test environment and using http://localhost:3000, you would use http://localhost:3000/api/auth/callback
36
37
 
37
38
  ### 1. Set up routes
38
39
 
39
40
  In your `src/app/api/auth/[slug]` directory, create a file called `route.ts` with the following content:
40
41
 
41
42
  ```typescript
42
- import {getRouteHandlers} from "@propelauth/nextjs/server/app-router";
43
- import {NextRequest} from "next/server";
43
+ import { getRouteHandlers } from '@propelauth/nextjs/server/app-router'
44
+ import { NextRequest } from 'next/server'
44
45
 
45
46
  // postLoginRedirectPathFn is optional, but if you want to redirect the user to a different page after login, you can do so here.
46
47
  const routeHandlers = getRouteHandlers({
47
48
  postLoginRedirectPathFn: (req: NextRequest) => {
48
- return "/"
49
- }
49
+ return '/'
50
+ },
50
51
  })
51
52
  export const GET = routeHandlers.getRouteHandler
52
53
  export const POST = routeHandlers.postRouteHandler
53
54
  ```
54
55
 
55
- ### 2. Set up AuthProvider
56
+ ### 2. Set up AuthProvider
56
57
 
57
- #### App Router
58
+ #### App Router
58
59
 
59
60
  In your root layout, `src/app/layout.tsx`, add the `AuthProvider`:
60
61
 
@@ -89,7 +90,7 @@ export default function MyApp({Component, pageProps}: AppProps) {
89
90
  In your `src/middleware.ts` file, add the following:
90
91
 
91
92
  ```typescript
92
- import {authMiddleware} from "@propelauth/nextjs/server/app-router";
93
+ import { authMiddleware } from '@propelauth/nextjs/server/app-router'
93
94
 
94
95
  export const middleware = authMiddleware
95
96
 
@@ -110,11 +111,11 @@ export const config = {
110
111
  ### Get the user in Server Components (App Router example)
111
112
 
112
113
  ```tsx
113
- import {getUser} from "@propelauth/nextjs/server/app-router";
114
+ import { getUser } from '@propelauth/nextjs/server/app-router'
114
115
 
115
116
  const WelcomeMessage = async () => {
116
117
  const user = await getUser()
117
-
118
+
118
119
  if (user) {
119
120
  return <div>Hello {user.firstName}!</div>
120
121
  } else {
@@ -124,12 +125,12 @@ const WelcomeMessage = async () => {
124
125
  ```
125
126
 
126
127
  ```tsx
127
- import {getUserOrRedirect} from "@propelauth/nextjs/server/app-router";
128
+ import { getUserOrRedirect } from '@propelauth/nextjs/server/app-router'
128
129
 
129
130
  const WelcomeMessage = async () => {
130
131
  // If the user is not logged in, they will be redirected to the login page
131
132
  const user = await getUserOrRedirect()
132
-
133
+
133
134
  return <div>Hello {user.firstName}!</div>
134
135
  }
135
136
  ```
@@ -137,11 +138,11 @@ const WelcomeMessage = async () => {
137
138
  ### Get the user in getServerSideProps (Pages example)
138
139
 
139
140
  ```tsx
140
- import {GetServerSideProps, InferGetServerSidePropsType} from "next";
141
- import {getUserFromServerSideProps} from "@propelauth/nextjs/server/pages";
142
- import {User} from "@propelauth/nextjs/client";
141
+ import { GetServerSideProps, InferGetServerSidePropsType } from 'next'
142
+ import { getUserFromServerSideProps } from '@propelauth/nextjs/server/pages'
143
+ import { User } from '@propelauth/nextjs/client'
143
144
 
144
- export default function WelcomeMessage({userJson}: InferGetServerSidePropsType<typeof getServerSideProps>) {
145
+ export default function WelcomeMessage({ userJson }: InferGetServerSidePropsType<typeof getServerSideProps>) {
145
146
  // Deserialize the user from the JSON string so you can call functions like user.getOrg()
146
147
  const user = User.fromJSON(userJson)
147
148
  return <div>Hello, {user.firstName}</div>
@@ -150,24 +151,24 @@ export default function WelcomeMessage({userJson}: InferGetServerSidePropsType<t
150
151
  export const getServerSideProps: GetServerSideProps = async (context) => {
151
152
  const user = await getUserFromServerSideProps(context)
152
153
  if (!user) {
153
- return {redirect: {destination: '/api/auth/login', permanent: false}}
154
+ return { redirect: { destination: '/api/auth/login', permanent: false } }
154
155
  }
155
- return { props: {userJson: JSON.stringify(user) } }
156
+ return { props: { userJson: JSON.stringify(user) } }
156
157
  }
157
158
  ```
158
159
 
159
160
  ### Get the user in API Routes (Pages example)
160
161
 
161
162
  ```ts
162
- import {NextApiRequest, NextApiResponse} from "next";
163
- import {getUserFromApiRouteRequest} from "@propelauth/nextjs/server/pages";
163
+ import { NextApiRequest, NextApiResponse } from 'next'
164
+ import { getUserFromApiRouteRequest } from '@propelauth/nextjs/server/pages'
164
165
 
165
166
  export default async function handler(req: NextApiRequest, res: NextApiResponse) {
166
167
  const user = await getUserFromApiRouteRequest(req, res)
167
168
  if (user) {
168
- res.status(200).json({email: user.email})
169
+ res.status(200).json({ email: user.email })
169
170
  } else {
170
- res.status(401).json({error: "unauthorized"})
171
+ res.status(401).json({ error: 'unauthorized' })
171
172
  }
172
173
  }
173
174
  ```
@@ -175,13 +176,13 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
175
176
  ### Get the user in Client Components
176
177
 
177
178
  ```tsx
178
- "use client";
179
+ 'use client'
179
180
 
180
- import {useUser} from "@propelauth/nextjs/client";
181
+ import { useUser } from '@propelauth/nextjs/client'
181
182
 
182
183
  const WelcomeMessage = () => {
183
- const {loading, user} = useUser()
184
-
184
+ const { loading, user } = useUser()
185
+
185
186
  if (loading) {
186
187
  return <div>Loading...</div>
187
188
  } else if (user) {
@@ -198,23 +199,28 @@ Note that this works on both the client's `User` object or the client/server `Us
198
199
 
199
200
  If you are curious where the organization information comes from, check out our documentation on [organizations](https://docs.propelauth.com/overview/organizations?utm_source=github&utm_medium=library&utm_campaign=nextjs).
200
201
  The quick answer is:
202
+
201
203
  - PropelAuth provides UI for users to create organizations and invite other users to join them.
202
204
  - Your users can also create Enterprise SSO/SAML connections to their own Identity Providers (IdPs) so their organization members can log in with their existing work credentials.
203
205
  - You can create organizations and add users to them via our APIs or our Dashboard.
204
206
 
205
207
  ```tsx
206
208
  // src/app/org/[slug]/page.tsx
207
- import {getUserOrRedirect} from "@propelauth/nextjs/server/app-router";
209
+ import { getUserOrRedirect } from '@propelauth/nextjs/server/app-router'
208
210
 
209
211
  export default async function AdminOnlyPage({ params }: { params: { slug: string } }) {
210
212
  const user = await getUserOrRedirect()
211
- const org = user.getOrgByName(params.slug);
212
- const isAdmin = org?.isRole("Admin")
213
+ const org = user.getOrgByName(params.slug)
214
+ const isAdmin = org?.isRole('Admin')
213
215
 
214
216
  if (!isAdmin) {
215
217
  return <div>Not found</div>
216
218
  } else {
217
- return <div>Welcome {user.firstName}, Admin of {org?.orgName}</div>
219
+ return (
220
+ <div>
221
+ Welcome {user.firstName}, Admin of {org?.orgName}
222
+ </div>
223
+ )
218
224
  }
219
225
  }
220
226
  ```
@@ -222,9 +228,9 @@ export default async function AdminOnlyPage({ params }: { params: { slug: string
222
228
  ### Logging out
223
229
 
224
230
  ```tsx
225
- "use client"
231
+ 'use client'
226
232
 
227
- import {useLogoutFunction} from "@propelauth/nextjs/client";
233
+ import { useLogoutFunction } from '@propelauth/nextjs/client'
228
234
 
229
235
  export default function LogoutButton() {
230
236
  const logoutFn = useLogoutFunction()
@@ -237,35 +243,39 @@ export default function LogoutButton() {
237
243
  If you don't want to use redirect functions, you can also use `useHostedPageUrls` which will return the URLs instead of redirecting.
238
244
 
239
245
  ```tsx
240
- "use client"
246
+ 'use client'
241
247
 
242
- import {useRedirectFunctions} from "@propelauth/nextjs/client";
248
+ import { useRedirectFunctions } from '@propelauth/nextjs/client'
243
249
 
244
250
  export default function SignupAndLoginButtons() {
245
- const {redirectToSignupPage, redirectToLoginPage} = useRedirectFunctions()
246
- return <>
247
- <button onClick={redirectToSignupPage}>Sign up</button>
248
- <button onClick={redirectToLoginPage}>Log in</button>
249
- </>
251
+ const { redirectToSignupPage, redirectToLoginPage } = useRedirectFunctions()
252
+ return (
253
+ <>
254
+ <button onClick={redirectToSignupPage}>Sign up</button>
255
+ <button onClick={redirectToLoginPage}>Log in</button>
256
+ </>
257
+ )
250
258
  }
251
259
  ```
252
260
 
253
261
  ### Redirecting to Account / Org pages
254
262
 
255
- PropelAuth also provides you with pre-built account and organization management UIs.
263
+ PropelAuth also provides you with pre-built account and organization management UIs.
256
264
  You can redirect your users to these pages by using the following functions:
257
265
 
258
266
  ```tsx
259
- "use client"
267
+ 'use client'
260
268
 
261
- import {useRedirectFunctions} from "@propelauth/nextjs/client";
269
+ import { useRedirectFunctions } from '@propelauth/nextjs/client'
262
270
 
263
271
  export default function AccountAndOrgButtons() {
264
- const {redirectToAccountPage, redirectToOrgPage} = useRedirectFunctions()
265
- return <>
266
- <button onClick={redirectToAccountPage}>Account</button>
267
- <button onClick={redirectToOrgPage}>Organization</button>
268
- </>
272
+ const { redirectToAccountPage, redirectToOrgPage } = useRedirectFunctions()
273
+ return (
274
+ <>
275
+ <button onClick={redirectToAccountPage}>Account</button>
276
+ <button onClick={redirectToOrgPage}>Organization</button>
277
+ </>
278
+ )
269
279
  }
270
280
  ```
271
281
 
@@ -274,7 +284,7 @@ export default function AccountAndOrgButtons() {
274
284
  You can use our [APIs](https://docs.propelauth.com/reference/backend-apis/node) like so:
275
285
 
276
286
  ```ts
277
- import {getPropelAuthApis} from "@propelauth/nextjs/server";
287
+ import { getPropelAuthApis } from '@propelauth/nextjs/server'
278
288
 
279
289
  const apis = getPropelAuthApis()
280
290
  await apis.disableUser(userId)
@@ -286,13 +296,13 @@ PropelAuth also supports backend that are not Next.js. To make an [authenticated
286
296
  to an external API, you'll need an access token. You can get an access token on the frontend from the `useUser` hook:
287
297
 
288
298
  ```tsx
289
- import {useUser} from "@propelauth/nextjs/client";
299
+ import { useUser } from '@propelauth/nextjs/client'
290
300
 
291
301
  const MyComponent = () => {
292
- const {loading, accessToken} = useUser()
293
-
302
+ const { loading, accessToken } = useUser()
303
+
294
304
  // Make a request to an external API with useEffect, useQuery, etc.
295
305
  }
296
306
  ```
297
307
 
298
- Within the App Router, you can also call `getAccessToken` to get the access token.
308
+ Within the App Router, you can also call `getAccessToken` to get the access token.
@@ -344,7 +344,7 @@ function getAuthUrlOrigin() {
344
344
  return getAuthUrl().origin;
345
345
  }
346
346
  function getAuthUrl() {
347
- const authUrl = process.env.NEXT_PUBLIC_AUTH_URL;
347
+ const authUrl = process.env.PROPELAUTH_AUTH_URL || process.env.NEXT_PUBLIC_AUTH_URL;
348
348
  if (!authUrl) {
349
349
  throw new Error("NEXT_PUBLIC_AUTH_URL is not set");
350
350
  }
@@ -737,8 +737,10 @@ function getRouteHandlers(args) {
737
737
  headers: headers2
738
738
  });
739
739
  } else if (response.status === 401) {
740
+ const apiKey = getIntegrationApiKey();
741
+ const firstFourChars = apiKey.substring(0, 4);
740
742
  console.error(
741
- "Couldn't finish the login process for this user. This is most likely caused by an incorrect PROPELAUTH_API_KEY."
743
+ `Couldn't finish the login process for this user. This is most likely caused by an incorrect PROPELAUTH_API_KEY. Your API key starts with ${firstFourChars}... double check that that matches the API key in the PropelAuth dashboard for this environment.`
742
744
  );
743
745
  return new Response("Unexpected error", { status: 500 });
744
746
  } else {