I have a middleware for auth.
Basically the middleware handles the authentication.
ctx.pathname returning the wrong value. For example, if I request http://localhost:4001/student/courses/bd478029-2493-4602-9047-ab4ed83f4538 this url on the browser then it's returning /login instead /student/courses/[id]. But, for http://localhost:4001/login its returning as the value as expected i.e: /login
What's going on?
Here is my authMiddleware.js code
import { studentHome, studentLogin, teacherHome, teacherLogin } from "../utils/staticFields";
import redirectTo from "./redirectTo"
import UserManager from "./UserManager";
const authMiddleware = ctx => {
try {
console.log('@@@@@', ctx.pathname, Date.now())
const user = UserManager.getCookie('user',ctx)
const userObj = user ? JSON.parse(user) : null;
let redirectUrl = ""
// const prevUrl = ctx.asPath
if(userObj){
if(userObj.type === "teacher" && (!ctx.pathname.startsWith("/teacher") || ctx.pathname === "/teacher/login")) redirectUrl = teacherHome; // user is logged in, redirect to teacher portal
else if(userObj.type === "student" && !ctx.pathname.startsWith("/student")) redirectUrl = studentHome; // user is logged in, redirect to student portal
} else if(!userObj && ctx.pathname.startsWith("/teacher") && ctx.pathname !== "/teacher/login"){
redirectUrl = teacherLogin; // user is not logged in, redirect to login (teacher)
} else if(!userObj && ctx.pathname.startsWith("/student")){
// UserManager.setIntendedUrl(ctx,prevUrl)
redirectUrl = studentLogin; // user is not logged in, redirect to login (student)
}
if(redirectUrl){
console.log("REDIRECTING FROM", ctx.pathname, "TO", redirectUrl)
redirectTo(redirectUrl, { res: ctx.res, status: 301 });
}
} catch (error) {
console.error("Error in authMiddleware", error)
}
}
export default authMiddleware
_app.js
...
MyApp.getInitialProps = async ({ Component, ctx }) => {
const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {};
authMiddleware(ctx);
return { pageProps }
}