Next.js Discord

Discord Forum

Middleware in next js 12.2

Unanswered
Gazami crab posted this in #help-forum
Open in Discord
Gazami crabOP
hey guys I am trying to implement middleware in my next js 12.2. I have created middleware.tsx file inside pages folder and used this code.
// eslint-disable-next-line @next/next/no-server-import-in-page
import { NextRequest, NextResponse } from "next/server";

export function middleware(request: NextRequest) {
  console.log(request);
  return NextResponse.redirect(new URL("/auth/signup/email", request.url));
}

export const config = {
  matcher: "/",
};

but nothig is happening nor I am getting any error. please let me how should I configure it with next 12.2

7 Replies

Asian black bear
I don't think the middleware file is supposed to go in /pages, it should be in /src if you have it, otherwise in the project root.
@Asian black bear I don't think the middleware file is supposed to go in `/pages`, it should be in `/src` if you have it, otherwise in the project root.
Gazami crabOP
Sir lets say I have put in my middleware.tsx file where .env is. I dont have src folder. Do I have to add anything in next config
Actually I want to add protected feature using middleware and my user object is in redux state so thinking of setting user object in cookie when user login and than get access to that cookie in middleare
Gazami crabOP
Sir it would be very helpful if you help me out. 🙏🙏 @Asian black bear
@Gazami crab Sir lets say I have put in my middleware.tsx file where .env is. I dont have src folder. Do I have to add anything in next config
Asian black bear
In next 13 it just works, i am not sure about 12. Middleware was more new then
@Asian black bear In next 13 it just works, i am not sure about 12. Middleware was more new then
Gazami crabOP
yes sir, the company where I am working is using next 12.2 and storing user session in redux state. now they want protected routes. I was thinking of using useEffect on pages to check the auth session but they have lot of pages and its hard to put same logic on every pages