K
Kindemoroshko

Protecting routes in Next.js App Router middleware

Docs at https://kinde.com/docs/developer-tools/nextjs-sdk/#protect-routes-using-middleware mention:
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.
Should I read this as "currently, protecting routes in the middleware doesn't work, and the code examples mentioned in this docs section won't work either"? When the user is signed out, and I navigate to http://localhost:3000, I can see that the middleware is hit with the api/auth/login pathname.
// middleware.ts

import { withAuth } from "@kinde-oss/kinde-auth-nextjs/middleware";
import { NextRequest } from "next/server";

export default function middleware(req: NextRequest) {
console.log("middleware =>", req.nextUrl.pathname);

return withAuth(req);
}
// middleware.ts

import { withAuth } from "@kinde-oss/kinde-auth-nextjs/middleware";
import { NextRequest } from "next/server";

export default function middleware(req: NextRequest) {
console.log("middleware =>", req.nextUrl.pathname);

return withAuth(req);
}
So, I'm trying to understand what exactly is not working in the middleware. On another note, withAuth() doesn't seem to be properly typed. Any plans to have proper types so that we could see for example what type publicPaths is in the middleware options? I could probably guess that it's an array of strings, but no idea for example if regex is supported. Having some examples in the docs would also help πŸ™‚
Kinde Docs
NextJS App Router SDK - Developer tools - Help center
Our developer tools provide everything you need to get started with Kinde.
Claire_Kinde
Claire_Kindeβ€’18d ago
Hey Misha. Checking if this is blocking you? Or if this is mainly suggestions for improving docs? Just so I know what I need to do next.
moroshko
moroshkoβ€’18d ago
Yes, blocking, as I don't understand what to expect from the middleware. As mentioned above, I'm confused about this:
middleware in the app router does not work when trying to redirect to api/auth/login
Improving the TypeScript types on the other hand is a nice to have (not blocking).
Claire_Kinde
Claire_Kindeβ€’18d ago
Okay thanks. Will see if I can get an eng to answer on this.
Peteswah
Peteswahβ€’18d ago
The docs are out of date! We will update it with more info about the middleware At the moment you can use the middleware like this:
import { withAuth } from "@kinde-oss/kinde-auth-nextjs/middleware";

export default withAuth(
async function middleware(req: any) {
// post login callback
console.log("LOOK AT ME");
},
{
loginPage: "/login",
}
);

export const config = {
matcher: ["/dashboard"],
};
import { withAuth } from "@kinde-oss/kinde-auth-nextjs/middleware";

export default withAuth(
async function middleware(req: any) {
// post login callback
console.log("LOOK AT ME");
},
{
loginPage: "/login",
}
);

export const config = {
matcher: ["/dashboard"],
};
moroshko
moroshkoβ€’17d ago
I'd like to understand how to do custom redirect rules in the middleware based on user permissions and requested url. Is it possible at the moment? Since the middleware runs in the Edge runtime, I wonder if I can just import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server"; and get the user from the server session? Does @kinde-oss/kinde-auth-nextjs/server support the Edge runtime or only Node?
Peteswah
Peteswahβ€’17d ago
Should be able to use getKindeServerSession in middleware
Peteswah
Peteswahβ€’17d ago
custom redirect rules can be done like this:
import {withAuth} from "@kinde-oss/kinde-auth-nextjs/middleware";
export default withAuth(
async function middleware(req) {
console.log("look at me", req.kindeAuth);
},
{
isReturnToCurrentPage: true,
loginPage: "/login",
isAuthorized: ({token}) => {
// The user will be considered authorized if they have the permission 'eat:chips'
return token.permissions.includes("eat:chips");
}
}
);

export const config = {
matcher: ["/admin"]
};
import {withAuth} from "@kinde-oss/kinde-auth-nextjs/middleware";
export default withAuth(
async function middleware(req) {
console.log("look at me", req.kindeAuth);
},
{
isReturnToCurrentPage: true,
loginPage: "/login",
isAuthorized: ({token}) => {
// The user will be considered authorized if they have the permission 'eat:chips'
return token.permissions.includes("eat:chips");
}
}
);

export const config = {
matcher: ["/admin"]
};
https://kinde.com/docs/developer-tools/nextjs-sdk/#protecting-routes
Kinde Docs
NextJS App Router SDK - Developer tools - Help center
Our developer tools provide everything you need to get started with Kinde.
moroshko
moroshkoβ€’16d ago
How would I do a redirect with this approach? e.g. if the user has a certain claim I want to redirect to /foo ?
Want results from more Discord servers?
Add your server
More Posts
User's first and last names are overridden when user logs in using GoogleAfter user signs up using Google, their first and last names in KindeUser are pre-populated from the`await getUser()` doesn't return the first and last nameIn my Next.js App Router application, in a page component, I get the user: ``` const { getUser } = gDoes Kinde provide Login/SignUp components for custom Login/SignUp pages?I'd like to have a custom `myapp.com/login` page in Next.js App Router application, and render a LogSubscribe Form...React[solved] Hi, I want to include the subscribe form in a react (docusaurus) site. I want to have a buRevoke all access tokens from KindeHi, May I know how to revoke all access tokens from Kinde?Separate login per organizationI'm working on a multi-tenant application. I would like to allow the users to register per organizatKinde Management apiDid I misunderstood something here ? I'm trying to create a user with the role "user", but Kinde doProtect Next.js route handlers with machine-to-machine application?Hi, I want to expose the route handlers defined in Next.js 14 application for external applicationsLogout button doesn't renderedI have implemented user auth using kinde successfully and my ecommerce website is able to login andChaining Middlewares Next.JS Kinde + next-internationalHi, as the title says I'm struggling to figure out how to use two different Next.js middlewares togeHas anyone used kinde_flutter_sdk to build android app?I am having issues building android APK with kinde_flutter_sdk for auth. I install the SDK and withoUnable to login to our dashboard in KindeHello, I'm getting this error when I sign in to my account 404 Domain not found The requested domaiBilling feature launch dateWhen will the billing feature be available to integrate and use. At least give the tentative dateWhat would be the most secure way to create invitation link for users to join an organizations ?I'm using resend to send the invitation link (Nextjs app router SDK). The link should be created witDoes the expo/RN SDK work with react native web?Hi, I am starting a new project and wanted to know if the Expo SDK supports React Native Web?How to prefill "First name" and "Last name" like we can do email with "login_hint"We have a custom authentication page. So email/first name/last name are already curated. We are ableWhy I am getting this error , even though I have setup callback url and redirect url.eroor: The provided authorization grant (e.g., authorization code, resource owner credentials) or reSAML per organization - estimation https://updates.kinde.com/board/set-authentication-options-per-orDo you guys have an estimation for this ticket? https://updates.kinde.com/board/set-authentication-oadd user in mongodb database on nuxtHey, I'm currently trying to create a nuxt app. The login is working but I don't know how I can add work email verificationHi, We have been using kinde for our applications and it’s awesome. Thanks for this wonderful tool.