Next.js Discord

Discord Forum

How to use middleware.js?

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
src/app is my directory structure
src/app/login,
src/app/dashboard
so i moved middleware.js to /src directory and app/login directory

But i wanted to have different login for front end and backend

but new directory structure its not working
/src/app/dashboard
/src/app/dashboard/login

with
http://localhost:3000/dashboard/login?callbackUrl=http%3A%2F%2Flocalhost%3A3000%2Fdashboard%2Flogin

Not worth . Auth is null because middleware.js not called.

so i copied middlewar.js in every directory and wanted to see if it work.

Nope. So i need to know how to fix this.

middleware.js
 
import NextAuth from "next-auth";
import { authConfig } from "@/lib/auth/authconfig";

export default NextAuth(authConfig).auth;

export const config = {
  matcher: ['/((?!api|static|.*\\..*|_next).*)'],
};

187 Replies

Spectacled bearOP
i neeed to have separate login for front end and backend
@Spectacled bear Click to see attachment
are you using userRouter from next/router?
Spectacled bearOP
nope
none of it
app/page.jsx
what is the issue are you facing?
Spectacled bearOP
i have app/login it works
but when i move app/login to app/dashboard/login it is not getting auth from middleware.js . its null
auth is not coming from middleware.js
Spectacled bearOP
it is
no
middleware only protect the route
Spectacled bearOP
import NextAuth from "next-auth";
import { authConfig } from "@/lib/auth/authconfig";

export default NextAuth(authConfig).auth;

export const config = {
  matcher: ['/((?!api|static|.*\\..*|_next).*)'],
};
you call auth() to get the session if the user is logged in
Spectacled bearOP
instead of putting in every code
its in middleware.js
yes it look good
but you should only have one in src/middleware.js
Spectacled bearOP
i put it in app/login it work
it is doing nothing in app/login/middleware
Spectacled bearOP
no no
it should also work if you remove it
Spectacled bearOP
middleware.js is in /src
if login is in app/dashboard/login its not working
could you show the code
and the error
Spectacled bearOP
are you logged in yet?
Spectacled bearOP
Layout basically calls sidebar. its nothing to do with sidebar but sidebar is first one call auth
i can move the code to layout
import { auth, signOut } from "@/lib/auth/auth";
const {user} = await auth();
those methods
auth is null
because you are not logged in right?
Spectacled bearOP
try const {user} = await auth()|| {};
Spectacled bearOP
i logged out and try to login from /dashboard/login
but if i do /login it works
because auth() return Session or null
you can't destruct null value
so use this instead
const {user} = await auth()|| {};
and the user will be null if you are not logged in
Spectacled bearOP
question is why its null
its not null when i use /login
its null if you are not logged in
Spectacled bearOP
we can only take out side bar
@Spectacled bear we can only take out side bar
you want to hide sidebar if the user is not logged in right?
Spectacled bearOP
watch this
when i call /login directly
ignore loss of style
its automatically switch to specific login screen
Im confused
do you mean you go to /login and it redirect you to other screen?
Spectacled bearOP
from /login i see this
front /dashboard/login it kinda broken
As you can see i have login folder in app and app/dashboard
its same code
it call same everything
@Spectacled bear Click to see attachment
you don't need to import css here
Spectacled bearOP
just so it same color
just import it in app/layout.jsx
Spectacled bearOP
ignore that for now
no
i don't get it what is the issue?
Spectacled bearOP
there is no app/layout.jsx
its app/dashboard/layout.jsx
it used that when its in dashboard/login
but i have auth null
@Spectacled bear there is no app/layout.jsx
this make me completely lost 😵
Spectacled bearOP
see the url plese
what wrong with it?
Spectacled bearOP
i think i need cut off dashboard/layout.js on login
how do i do it
ur null check was helpful. that removed error
now i need to rid of dashboard layout.jsx on login
create this folder app/dashboard/(nav)
then move these inside
app/dashboard/(nav)/layout.jsx
app/dashboard/(nav)/products
app/dashboard/(nav)/users
app/dashboard/(nav)/page.jsx
Spectacled bearOP
=== otherwise background of dashboard with so many checks
what is (nav)
like this?
no, login should be outside of it
move other route under dashboard inside (nav)
like this
app/dashboard/(nav)/layout.jsx
app/dashboard/(nav)/products
app/dashboard/(nav)/users
app/dashboard/(nav)/page.jsx
app/dashboard/login/page.jsx
Spectacled bearOP
error
what is (nav) not working
could you show the folder structure
Spectacled bearOP
copy this and paste it
(nav)
Spectacled bearOP
ok try it
Spectacled bearOP
still issues after login it stuck in same spot
what issue?
Spectacled bearOP
after login it did not go to dashboard
so i manually typed in
@Spectacled bear after login it did not go to dashboard
show the code in login
Spectacled bearOP
"use client";

import { authenticate } from "@/lib/database/dbcrud";
import styles from "./loginForm.module.css";
import { useFormState } from "react-dom";

const LoginForm = () => {
  const [state, formAction] = useFormState(authenticate, undefined);

  return (
    <form id="login" action={formAction} className={styles.form}>
      <h1>Login</h1>
      <input type="text" placeholder="username" name="username" />
      <input type="password" placeholder="password" name="password" />
      <button>Login</button>
      {state && state}
    </form>
  );
};

export default LoginForm;
Spectacled bearOP
`
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { authConfig } from "./authconfig";
import { connectToDB } from "@/lib/database/dbconfig";
import { User } from "@/lib/database/schema/models";
import bcrypt from "bcrypt";




const login = async (credentials) => {
  try {
    connectToDB();
    const user = await User.findOne({ username: credentials.username });

    if (!user || !user.isAdmin) throw new Error("Wrong credentials!");



    const isPasswordCorrect = await bcrypt.compare(
      credentials.password,
      user.password,
    );

    if (!isPasswordCorrect) throw new Error("Wrong credentials Password!");

    return user;
  } catch (err) {
    console.log(err);
    throw new Error("Failed to login!");
  }
};

export const { signIn, signOut, auth } = NextAuth({
  ...authConfig,
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        try {
          const user = await login(credentials);
          return user;
        } catch (err) {
          return null;
        }
      },
    }),
  ],
  // ADD ADDITIONAL INFORMATION TO SESSION
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.username = user.username;
        token.img = user.img;
      }
      return token;
    },
    async session({ session, token }) {
      if (token) {
        session.user.username = token.username;
        session.user.img = token.img;
      }
      return session;
    },
  },
});

auth.js is where all happens
Auth config
export const authConfig = {
  providers:[],
  pages: {
    signIn: "/dashboard/login",
  },
  callbacks: {
    authorized({ auth, request }) {

      const isLoggedIn = auth?.user;
      const isOnDashboard = request.nextUrl.pathname.startsWith("/dashboard");

//      console.log("\n\n\n isOnDashboard : "+isOnDashboard+'\n\n')
      if (isOnDashboard) {
        if (isLoggedIn) return true;
        return false;
      } else if (isLoggedIn) {
        return Response.redirect(new URL("/dashboard", request.nextUrl));
      }
      return true;
    },
  },
};
Spectacled bearOP
not really we still have problem in two places
I am infact logged in . it should not go to form
it need tobe checked in login page itself
also when i submit
@Spectacled bear I am infact logged in . it should not go to form
use redirect in authenticate in @/lib/database/dbcrud"
or show the code on authenticate
Spectacled bearOP
all authenticate happen in above files
i can check if its logged in
but how do i redirect in loginform
import styles from "@/dashboard/ui/login/login.module.css";
import LoginForm from "@/dashboard/ui/login/loginForm/loginForm";
import '@/dashboard/ui/globals.css'
import { auth, signOut } from "@/lib/auth/auth";
const {user} = await auth()|| {};


const LoginPage = () => {
  if(user)  
  return (
    <div className={styles.container}>
      <LoginForm/>
    </div>
  );
};

export default LoginPage;
my new login
but need to redirect to dashboard
why are you using auth() outside of component
import styles from "@/dashboard/ui/login/login.module.css";
import LoginForm from "@/dashboard/ui/login/loginForm/loginForm";
import '@/dashboard/ui/globals.css'
import { auth, signOut } from "@/lib/auth/auth";
import { redirect } from 'next/navigation';

const LoginPage = () => {
  const session = await auth();
  if(session) redirect("/dashboard")

  return (
    <div className={styles.container}>
      <LoginForm/>
    </div>
  );
};

export default LoginPage;
change to this
Spectacled bearOP
that wont work
what is not working?
what error do you see
oh ok i see the error
@Spectacled bear that wont work
try this
import styles from "@/dashboard/ui/login/login.module.css";
import LoginForm from "@/dashboard/ui/login/loginForm/loginForm";
import '@/dashboard/ui/globals.css'
import { auth, signOut } from "@/lib/auth/auth";
import { redirect } from 'next/navigation';

const LoginPage = async () => {
  const session = await auth();
  if(session) redirect("/dashboard")

  return (
    <div className={styles.container}>
      <LoginForm/>
    </div>
  );
};

export default LoginPage;
Spectacled bearOP
one sec
it keep giving error
what error?
Spectacled bearOP
congrats
But i need one more issue
what issue?
Spectacled bearOP
how do i solve frontend folder
i want label for frontend
(nav) on front end is ugly
what do you mean?
Spectacled bearOP
Website home page
(frontend) then
what is inside frontend?
Spectacled bearOP
home page
sites page
ok
yea you could do that
Spectacled bearOP
just like wordpress
Spectacled bearOP
not worky
could you show the folder again
Spectacled bearOP
oops i stopped server
let me start
should work becauise its same as before
ok
does it work?
Spectacled bearOP
new error
did you move lib folder?
Spectacled bearOP
oops i deleted some directory
whole lib
damn
lol
restore it
from trash
Spectacled bearOP
its all gone
whole thing not even in recyclebin
grab it from here
Spectacled bearOP
try to delete login from src
deleted lib
This is from lamadev example ...
i am just changing everything bevause i am making my own admin and front end for my php website which i built in 2014
I want to create scaffolding for all mongo db documents
All document will have some standard fields ...and add additional custom field laters
I also have my own custom sql if mongodb dont work. i need to figure out how to convert my relational data into mongodb documents structure
anyway thanks for help!!! very much appreciated.

I have long way to go before everything work. I only started today seriously to fix all project structure. Then i will clean up more.

I need to create Responsive Design using Tailwind css .. i was doing that then i thought i fix project structure first
=============== (frontend) issue still not solved. It still going to login page as thought i typed /dashboard
{
  /*
  "compilerOptions": {
    "paths": {
      "@/*": ["./*"]
    }
  }
  */

  "compilerOptions": {
    "baseUrl": "src/",
    "paths": {
      "@/app/*": ["app/*"],
      "@/lib/*": ["lib/*"],
      "@/styles/*": ["styles/*"],
      "@/components/*": ["components/*"],


      "@/dashboard/*": ["components/dashboard/*"],
      "@/frontend/*": ["components/frontend/*"]
    }
  }
  
   /*
  "compilerOptions": {
    "baseUrl": "src/",
    "paths": {
      "@/*": ["./*"]
    }
  }
  */

}
ok all work! thanks
i did vite react 6month ago. What you think?
http://jupiterrules.com.s3-website-us-west-2.amazonaws.com/
my first react project i did to learn stuff.
Then i become lazy fixing php stuff.

Now i am seriously converting php to react
Not for mobile , for desktop to run with nwjs
to slim down windows with essential services