Chaining Middlewares Next.JS Kinde + next-international
Hi, as the title says I'm struggling to figure out how to use two different Next.js middlewares together.
Has anyone tried this Using the Kinde middleware + something else.
Or am I approaching this the wrong way?
Thank you
6 Replies
Hi there. Here's some recommendations for how to approach this:
1. Combine Middleware Functions: You can combine multiple middleware functions into a single middleware module. This allows you to apply different authentication and authorization checks or other functionalities in a sequential manner.
2. Use withAuth Middleware: Utilize the withAuth middleware provided by Kinde for handling authentication. This middleware ensures that if a user is not authenticated, they are redirected to the login page.
3. Custom Middleware for Additional Logic: After setting up the withAuth middleware, you can create another custom middleware function to handle additional logic specific to your application needs. This could include user role checks, logging, or other custom behaviors.
4. Order of Middleware: Ensure the order of middleware is correct. Typically, authentication checks (like those provided by withAuth) should come before any other business logic checks. This ensures that only authenticated users can access certain functionalities.
5. Configuration in Next.js: Configure your middleware in the Next.js application by exporting them from a middleware file. Use the config object to specify which paths the middleware should apply to.
6. Testing: Thoroughly test the combined middleware to ensure that they work seamlessly together and do not interfere with each other’s operations.
Here’s a basic example of how you might set this up in your Next.js project:
// pages/_middleware.js
import { withAuth } from "@kinde-oss/kinde-auth-nextjs/middleware";
import customMiddleware from "../path/to/customMiddleware";
export default function middleware(req) {
withAuth(req);
customMiddleware(req);
}
export const config = {
matcher: ["/protected/*"]
};
Let us know if this helps. Or if you are still stuck.Thank you so much for the answer, I will try this out and get back to you
hi @WiESA did you solve the problem? If so, could you show the code?
Hi @Jan no not yet, had to remove the translation for now. Did you have the same issue?
Yes, I am using intl-middleware and auth-middleware from Kinde and all auth endpoints delivered by Kinde I have to exclude from the intl-middleware like following
Great, thank you for the answer!
@Jan I implemented it similar to you