Skip to content

Commit 75b1d3c

Browse files
authored
Merge pull request #305 from Yoshify/nextjs/2.5.0
feat: update documentation for version 2.5.0 of the Next.js SDK
2 parents 5cd1a48 + e447d76 commit 75b1d3c

File tree

1 file changed

+148
-69
lines changed

1 file changed

+148
-69
lines changed

src/content/docs/developer-tools/sdks/backend/nextjs-sdk.mdx

Lines changed: 148 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,143 @@ This will handle Kinde Auth endpoints in your Next.js app.
7676

7777
**Important!** Our SDK relies on this file existing in this location specified above.
7878

79+
## **Customising Kinde Auth API paths**
80+
81+
The default path for the Kinde Auth API is `/api/auth`. If your Next.js application uses a custom base path for your API, you can override this setting by setting the following variable in your `.env` file:
82+
83+
```bash
84+
KINDE_AUTH_API_PATH="/my/custom/path"
85+
```
86+
87+
You can also customise the Kinde Auth API sub-paths by setting the following variables in your `.env` file:
88+
89+
- `KINDE_AUTH_LOGIN_ROUTE` - defaults to `login`
90+
- `KINDE_AUTH_LOGOUT_ROUTE` - defaults to `logout`
91+
- `KINDE_AUTH_REGISTER_ROUTE` - defaults to `register`
92+
- `KINDE_AUTH_CREATEORG_ROUTE` - defaults to `create_org`
93+
- `KINDE_AUTH_HEALTH_ROUTE` - defaults to `health`
94+
- `KINDE_AUTH_SETUP_ROUTE` - defaults to `setup`
95+
96+
#### **Example**
97+
98+
Given the following `.env` file:
99+
100+
```bash
101+
KINDE_AUTH_API_PATH="/my/custom/path"
102+
KINDE_AUTH_LOGIN_ROUTE="app_login"
103+
```
104+
105+
The Kinde login route for your application will be `/my/custom/path/app_login`.
106+
107+
## **Set up middleware**
108+
109+
Middleware is used to protect routes in your Next.js app, and is a requirement for a seamless authentication experience.
110+
111+
We provide a `withAuth` helper that will protect routes covered by the matcher. If the user is not authenticated then they are redirected to login and once they have logged in they will be redirected back to the protected page which they should now have access to.
112+
113+
We require this middleware to run on all routes beside Next.js internals and static files. The provided matcher will do this for you.
114+
115+
This means that by default, all routes will be protected. You must opt-out public routes - see [opting routes out of middleware protection](#opting-routes-out-of-middleware-protection) for more information.
116+
117+
<Aside>
118+
119+
Want to learn more about middleware? Check out the [Next.js middleware docs](https://nextjs.org/docs/app/building-your-application/routing/middleware).
120+
121+
</Aside>
122+
123+
#### **Middleware configuration**
124+
125+
Create a `middleware.ts` file in your project's root directory and add the following code:
126+
```ts
127+
import { withAuth } from "@kinde-oss/kinde-auth-nextjs/middleware";
128+
129+
export default function middleware(req) {
130+
return withAuth(req);
131+
}
132+
133+
export const config = {
134+
matcher: [
135+
// Run on everything but Next internals and static files
136+
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
137+
]
138+
};
139+
```
140+
141+
#### **Route protection with callback function after authorization**
142+
143+
You can use the `withAuth` helper as shown below with a `middleware` callback function which has access to the `req.kindeAuth` object that exposes the token and user data.
144+
145+
```ts
146+
import {withAuth} from "@kinde-oss/kinde-auth-nextjs/middleware";
147+
148+
export default withAuth(async function middleware(req) {
149+
console.log("look at me", req.kindeAuth);
150+
});
151+
152+
export const config = {
153+
matcher: [
154+
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
155+
]
156+
};
157+
```
158+
159+
#### **Opting routes out of middleware protection**
160+
161+
As the middleware matcher is set to protect all routes, you can opt routes out of middleware protection by adding them to the `publicPaths` array.
162+
163+
```ts
164+
import { withAuth } from "@kinde-oss/kinde-auth-nextjs/middleware";
165+
166+
export default withAuth(
167+
async function middleware(req) {
168+
},
169+
{
170+
// Middleware still runs on all routes, but doesn't protect the blog route
171+
publicPaths: ["/blog"],
172+
}
173+
);
174+
175+
export const config = {
176+
matcher: [
177+
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
178+
],
179+
}
180+
```
181+
182+
#### **Additional middleware options**
183+
184+
There are options that can be passed into the middleware function to configure its functionality.
185+
186+
- `isReturnToCurrentPage` - redirect the user back to the page they were trying to access
187+
- `loginPage` - define the path of the login page (where the users are redirected to when not authenticated)
188+
- `publicPaths` - define the public paths
189+
- `isAuthorized` - define the criteria for authorization
190+
191+
```ts
192+
import { withAuth } from "@kinde-oss/kinde-auth-nextjs/middleware";
193+
194+
export default withAuth(
195+
async function middleware(req) {
196+
console.log("look at me", req.kindeAuth);
197+
},
198+
{
199+
isReturnToCurrentPage: true,
200+
loginPage: "/login",
201+
publicPaths: ["/public", '/more'],
202+
isAuthorized: ({token}) => {
203+
// The user will be considered authorized if they have the permission 'eat:chips'
204+
return token.permissions.includes("eat:chips");
205+
}
206+
}
207+
);
208+
209+
export const config = {
210+
matcher: [
211+
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
212+
],
213+
}
214+
```
215+
79216
## **Set up the Kinde Auth Provider**
80217

81218
Wrap your app in the Kinde Auth Provider. This will give you access to the Kinde Auth data in your app and will ensure that the tokens are refreshed when needed.
@@ -1340,87 +1477,29 @@ if (!(await isAuthenticated())) {
13401477
}
13411478
```
13421479

1343-
### Protect routes using middleware
1344-
1345-
You can also protect routes with Next.js middleware.
1346-
1347-
<Aside>
1348-
1349-
As of right now the middleware in the app router does not work when trying to redirect to `api/auth/login`. This is because of Next.js caching which causes issues during authentication.
1350-
1351-
</Aside>
1352-
1353-
**Default page protection**
1354-
1355-
We provide a `withAuth` helper that will protect routes covered by the matcher. If the user is not authenticated then they are redirected to login and once they have logged in they will be redirected back to the protected page which they should now have access to.
1356-
1357-
```jsx
1358-
import {withAuth} from "@kinde-oss/kinde-auth-nextjs/middleware";
1359-
export default function middleware(req) {
1360-
return withAuth(req);
1361-
}
1362-
export const config = {
1363-
matcher: ["/admin"]
1364-
};
1365-
```
1366-
1367-
**Page protection with callback function after authorization**
13681480

1369-
You can use the `withAuth` helper as shown below with a `middleware` callback function which has access to the `req.kindeAuth` object that exposes the token and user data.
1370-
1371-
```typescript
1372-
import {withAuth} from "@kinde-oss/kinde-auth-nextjs/middleware";
13731481

1374-
export default withAuth(async function middleware(req) {
1375-
console.log("look at me", req.kindeAuth);
1376-
});
1482+
## Refreshing Kinde data
13771483

1378-
export const config = {
1379-
matcher: ["/admin"]
1380-
};
1381-
```
1484+
Our middleware will automatically refresh the tokens in your session in the background.
13821485

1383-
**Middleware options**
1486+
Sometimes, you may want to refresh these tokens yourself. An example of this is when you update Kinde data via the UI or with the Management API.
13841487

1385-
There are options that can be passed into the middleware function to configure its functionality.
1488+
To have these updates immediately reflected in your app, you will need to get the most up-to-date Kinde data and then refresh the tokens in your session.
13861489

1387-
- `isReturnToCurrentPage` - redirect the user back to the page they were trying to access
1388-
- `loginPage` - define the path of the login page (where the users are redirected to when not authenticated)
1389-
- `publicPaths` - define the public paths
1390-
- `isAuthorized` - define the criteria for authorization
1490+
To get the most up-to-date Kinde data in your session, use the `refreshTokens` helper function provided by `getKindeServerSession`.
13911491

1392-
```typescript
1393-
import {withAuth} from "@kinde-oss/kinde-auth-nextjs/middleware";
1394-
export default withAuth(
1395-
async function middleware(req) {
1396-
console.log("look at me", req.kindeAuth);
1397-
},
1398-
{
1399-
isReturnToCurrentPage: true,
1400-
loginPage: "/login",
1401-
publicPaths: ["/public", '/more'],
1402-
isAuthorized: ({token}) => {
1403-
// The user will be considered authorized if they have the permission 'eat:chips'
1404-
return token.permissions.includes("eat:chips");
1405-
}
1406-
}
1407-
);
1492+
<Aside title="Important">
14081493

1409-
export const config = {
1410-
matcher: ["/admin"]
1411-
};
1412-
```
1413-
1414-
## Refreshing Kinde data
1494+
Due to limitations in Next.js, this will only work in a route handler or server action.
14151495

1416-
Kinde data can be updated via the UI or with the Management API. To have these updates be reflected in your app, you will need to get the most up-to-date Kinde data and then refresh the tokens in your session.
1417-
1418-
To get the most up-to-date Kinde data in your session, use the `refreshTokens` helper function.
1496+
</Aside>
14191497

1420-
```jsx
1421-
const {refreshTokens} = getKindeServerSession();
1498+
```tsx
1499+
'use server'
14221500

14231501
const handleRefresh = async () => {
1502+
const { refreshTokens } = getKindeServerSession();
14241503
await refreshTokens();
14251504
}
14261505

0 commit comments

Comments
 (0)