#How to use middleware.js?

188 messages · Page 1 of 1 (latest)

chrome carbon
#

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).*)'],
};

finite shadowBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

shy hawk
#

what do you mean by
/src/app/dashboard
/src/app/dashboard/login
is not working?

chrome carbon
#

i neeed to have separate login for front end and backend

shy hawk
chrome carbon
#

nope

#

none of it

#

app/page.jsx

shy hawk
#

what is the issue are you facing?

chrome carbon
#

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

shy hawk
#

auth is not coming from middleware.js

chrome carbon
#

it is

shy hawk
#

no

#

middleware only protect the route

chrome carbon
#
import NextAuth from "next-auth";
import { authConfig } from "@/lib/auth/authconfig";

export default NextAuth(authConfig).auth;

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

shy hawk
#

you call auth() to get the session if the user is logged in

chrome carbon
#

instead of putting in every code

#

its in middleware.js

shy hawk
#

yes it look good

#

but you should only have one in src/middleware.js

chrome carbon
#

i put it in app/login it work

shy hawk
#

it is doing nothing in app/login/middleware

chrome carbon
#

no no

shy hawk
#

it should also work if you remove it

chrome carbon
#

middleware.js is in /src

#

if login is in app/dashboard/login its not working

shy hawk
#

could you show the code

#

and the error

chrome carbon
shy hawk
#

are you logged in yet?

chrome carbon
#

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

shy hawk
#

because you are not logged in right?

#

try const {user} = await auth()|| {};

chrome carbon
#

i logged out and try to login from /dashboard/login

#

but if i do /login it works

shy hawk
#

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

chrome carbon
#

question is why its null

#

its not null when i use /login

shy hawk
#

its null if you are not logged in

chrome carbon
#

we can only take out side bar

shy hawk
chrome carbon
#

watch this

#

when i call /login directly

#

ignore loss of style

#

its automatically switch to specific login screen

shy hawk
#

Im confused

#

do you mean you go to /login and it redirect you to other screen?

chrome carbon
#

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

shy hawk
chrome carbon
#

just so it same color

shy hawk
#

just import it in app/layout.jsx

chrome carbon
#

ignore that for now

#

no

shy hawk
#

i don't get it what is the issue?

chrome carbon
#

there is no app/layout.jsx

#

its app/dashboard/layout.jsx

#

it used that when its in dashboard/login

#

but i have auth null

shy hawk
shy hawk
#

what wrong with it?

chrome carbon
#

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

shy hawk
#

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

chrome carbon
#

=== otherwise background of dashboard with so many checks

#

what is (nav)

#

like this?

shy hawk
#

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

chrome carbon
#

error

#

what is (nav) not working

shy hawk
#

could you show the folder structure

chrome carbon
shy hawk
#

copy this and paste it
(nav)

chrome carbon
shy hawk
#

ok try it

chrome carbon
#

still issues after login it stuck in same spot

shy hawk
#

what issue?

chrome carbon
#

after login it did not go to dashboard

#

so i manually typed in

shy hawk
chrome carbon
#

"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;
shy hawk
chrome carbon
#
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;
    },
  },
};

chrome carbon
#

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

shy hawk
#

or show the code on authenticate

chrome carbon
#

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

shy hawk
#

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

chrome carbon
#

that wont work

shy hawk
#

what is not working?

#

what error do you see

#

oh ok i see the error

shy hawk
# chrome carbon 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;
chrome carbon
#

one sec

#

it keep giving error

shy hawk
#

what error?

chrome carbon
#

congrats

#

But i need one more issue

shy hawk
#

what issue?

chrome carbon
#

how do i solve frontend folder

#

i want label for frontend

#

(nav) on front end is ugly

shy hawk
#

what do you mean?

shy hawk
chrome carbon
#

Website home page

#

(frontend) then

shy hawk
#

what is inside frontend?

chrome carbon
#

home page

#

sites page

shy hawk
#

ok

#

yea you could do that

chrome carbon
#

just like wordpress

chrome carbon
#

not worky

shy hawk
#

could you show the folder again

chrome carbon
#

oops i stopped server

#

let me start

#

should work becauise its same as before

shy hawk
#

ok

#

does it work?

chrome carbon
#

new error

shy hawk
#

did you move lib folder?

chrome carbon
#

oops i deleted some directory

#

whole lib

#

damn

shy hawk
#

lol

#

restore it

#

from trash

chrome carbon
#

its all gone

#

whole thing not even in recyclebin

shy hawk
#

grab it from here

chrome carbon
#

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

#

Not for mobile , for desktop to run with nwjs