NextJS and NextAuth
Unanswered
Hackberry nipple gall parasitoid posted this in #help-forum
Hackberry nipple gall parasitoidOP
Hello,
I'm trying to make a simple login and logout for my website which already has a dashboard that controls sensitive data, but, I'm not sure how to get started, I mostly need an username and password, and nothing else, has the username and password are autogenerated using a script that I made, What I use is Prisma with MongoDB, and I'm not sure how to make all of this simply, I know I have to use bcryptjs, nextauth, Prisma for Next auth.
What I need is someone who has already experience with those tools and helps me out.
Thanks
I'm trying to make a simple login and logout for my website which already has a dashboard that controls sensitive data, but, I'm not sure how to get started, I mostly need an username and password, and nothing else, has the username and password are autogenerated using a script that I made, What I use is Prisma with MongoDB, and I'm not sure how to make all of this simply, I know I have to use bcryptjs, nextauth, Prisma for Next auth.
What I need is someone who has already experience with those tools and helps me out.
Thanks
91 Replies
@Hackberry nipple gall parasitoid Hello,
I'm trying to make a simple login and logout for my website which already has a dashboard that controls sensitive data, but, I'm not sure how to get started, I mostly need an username and password, and nothing else, has the username and password are autogenerated using a script that I made, What I use is Prisma with MongoDB, and I'm not sure how to make all of this simply, I know I have to use bcryptjs, nextauth, Prisma for Next auth.
What I need is someone who has already experience with those tools and helps me out.
Thanks
Of the the stuff, that you need is described directly in this guide ([read more](https://next-auth.js.org/getting-started/example)). Follow the guide and you can easily setup a simple login
@B33fb0n3 Of the the stuff, that you need is described directly in this guide ([read more](https://next-auth.js.org/getting-started/example)). Follow the guide and you can easily setup a simple login
Hackberry nipple gall parasitoidOP
[next-auth][error][CLIENT_FETCH_ERROR] "\nhttps://next-auth.js.org/errors#client_fetch_error" "Failed to execute 'json' on 'Response': Unexpected end of JSON input" {}
I get this when I try to use signout..
@Hackberry nipple gall parasitoid [next-auth][error][CLIENT_FETCH_ERROR] "\nhttps://next-auth.js.org/errors#client_fetch_error" "Failed to execute 'json' on 'Response': Unexpected end of JSON input" {}
I get this when I try to use signout..
please share your current setup:
- Route handlers
- authOptions
- ...
- Route handlers
- authOptions
- ...
@B33fb0n3 please share your current setup:
- Route handlers
- authOptions
- ...
Hackberry nipple gall parasitoidOP
//options.ts
import type {NextAuthOptions} from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import prisma from "@/lib/prisma";
import bcrypt from "bcryptjs";
export const options: NextAuthOptions = {
providers: [CredentialsProvider({
name: "Credentials", credentials: {
username: {
label: "Username", type: "text", placeholder: "username"
}, password: {
label: "Password", type: "password", placeholder: "password"
}
}, async authorize(credentials) {
if (!credentials?.username || !credentials?.password) {
return null;
}
const user = await prisma.user.findUnique({
where: {username: credentials.username},
});
if (!user) {
console.error("Utente non trovato");
return null;
}
const isPasswordValid = await bcrypt.compare(credentials?.password, user.password);
if (!isPasswordValid) {
console.error("Password errata");
return null;
}
return {id: user.id.toString(), name: user.username};
}
})], pages: {
signIn: "/auth/login",
signOut: "/auth/login",
}, session: {
strategy: "jwt",
}, secret: process.env.NEXTAUTH_SECRET,
};
//route.ts
import NextAuth from "next-auth";
import {options} from "./options";
const handler = NextAuth(options)
export const {GET, POST} = handler;
//middleware.ts
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
export async function middleware(request: NextRequest) {
const token = await getToken({ req: request });
const { pathname } = request.nextUrl;
// Redirect unauthenticated users to login page
if (!token && pathname !== "/auth/login") {
return NextResponse.redirect(new URL("/auth/login", request.url));
}
// Redirect authenticated users to dashboard if they try to access login page
if (token && pathname === "/auth/login") {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/:path*"],
};
//scheme.prisma
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
username String @unique
password String
createdAt DateTime @default(now())
@@map("webapp_users")
}
yea thats all
login
//logout button
Button
className="mb-4"
onClick={() => signOut()}
>
Log out
</Button>
//restricted.ts
import {getServerSession} from "next-auth/next"
import {options} from "@/app/api/auth/[...nextauth]/options"
import {NextApiRequest, NextApiResponse} from 'next'
export default async function restrictedHandler(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, options)
if (session) {
res.send({
content: "This is protected content. You can access this content because you are signed in.",
})
} else {
res.send({
error: "You must be signed in to view the protected content on this page.",
})
}
}
@B33fb0n3 this is everything I think
@Hackberry nipple gall parasitoid <@301376057326567425> this is everything I think
thanks for sharing all the details.
Some things to do for you:
1. Can you remove the
2. Remove the
3. Are you using the app router or the pages router? Your folder structure looks like app router, but you using file syntax for pages router..
Btw, please format your files (for example with prettier).
Some things to do for you:
1. Can you remove the
restrictedHandler
for a moment and try again?2. Remove the
pages
in your options for a moment3. Are you using the app router or the pages router? Your folder structure looks like app router, but you using file syntax for pages router..
Btw, please format your files (for example with prettier).
@B33fb0n3 thanks for sharing all the details.
Some things to do for you:
1. Can you remove the `restrictedHandler` for a moment and try again?
2. Remove the pages in your options for a moment
3. Are you using the app router or the pages router? Your folder structure looks like app router, but you using file syntax for pages router..
Btw, please format your files (for example with prettier).
Hackberry nipple gall parasitoidOP
1. that isnt the problem i added it later, the logout not sure why its not working
2. what you mean about pages options?
3. im using the new things, I think .. ?, not sure first time doing something with nextjs
4. Im using webstorm and im using jetbrains formatter
2. what you mean about pages options?
3. im using the new things, I think .. ?, not sure first time doing something with nextjs
4. Im using webstorm and im using jetbrains formatter
@Hackberry nipple gall parasitoid 1. that isnt the problem i added it later, the logout not sure why its not working
2. what you mean about pages options?
3. im using the new things, I think .. ?, not sure first time doing something with nextjs
4. Im using webstorm and im using jetbrains formatter
1. ok
2. Inside your authOptions, there is a key in your object called
3. when creating pages inside the app router, you need to use the app router syntax. The syntax for a page is
4. You might need to configure your formatter a bit better 🙂
2. Inside your authOptions, there is a key in your object called
pages
. Delete it for a moment3. when creating pages inside the app router, you need to use the app router syntax. The syntax for a page is
page.tsx
4. You might need to configure your formatter a bit better 🙂
@B33fb0n3 1. ok
2. Inside your authOptions, there is a key in your object called `pages`. Delete it for a moment
3. when creating pages inside the app router, you need to use the app router syntax. The syntax for a page is `page.tsx`
4. You might need to configure your formatter a bit better 🙂
Hackberry nipple gall parasitoidOP
2. you mean this:
3. sorry i cannot understand what you mean, i feel pretty dumb
, pages: {
signIn: "/auth/login", signOut: "/auth/login",
}, session: {
strategy: "jwt",
}, secret: process.env.NEXTAUTH_SECRET,
3. sorry i cannot understand what you mean, i feel pretty dumb
Hackberry nipple gall parasitoidOP
btw not sure why the login page isnt style with css?
@Hackberry nipple gall parasitoid 2. you mean this:
ts
, pages: {
signIn: "/auth/login", signOut: "/auth/login",
}, session: {
strategy: "jwt",
}, secret: process.env.NEXTAUTH_SECRET,
3. sorry i cannot understand what you mean, i feel pretty dumb
2. no delete, like removing it. Like replacing the code with spaces. Like changing the letters to air. However you call it, just make the words vanish
3. Your folder contains a file called
3. Your folder contains a file called
_app.jsx
. That's pages router syntax. But you using the app router. So use app router syntax page.tsx
@B33fb0n3 2. no delete, like removing it. Like replacing the code with spaces. Like changing the letters to air. However you call it, just make the words vanish
3. Your folder contains a file called `_app.jsx`. That's pages router syntax. But you using the app router. So use app router syntax `page.tsx`
Hackberry nipple gall parasitoidOP
2. i have delete it, now?
3. I have change it to be page.tsx
3. I have change it to be page.tsx
this is the code of it
of that _app.tsx now as page.tsx
@Hackberry nipple gall parasitoid 2. i have delete it, now?
3. I have change it to be page.tsx
2. yea, delete it for a moment. Or uncomment it or whatever. Just make it dissapear for a moment
3. the code looks a bit weird, but should work
3. the code looks a bit weird, but should work
@B33fb0n3 2. yea, delete it for a moment. Or uncomment it or whatever. Just make it dissapear for a moment
3. the code looks a bit weird, but should work
Hackberry nipple gall parasitoidOP
[next-auth][error][CLIENT_FETCH_ERROR] "\nhttps://next-auth.js.org/errors#client_fetch_error" "Failed to execute 'json' on 'Response': Unexpected end of JSON input" {}
whyyy
:/
[ Server ] Error: Cannot read properties of undefined (reading 'session')
import { AppProps } from 'next/app';
import { SessionProvider } from 'next-auth/react';
import '@/app/globals.css';
function BloxStakes({ Component, pageProps }: AppProps) {
return (
<SessionProvider session={pageProps.session}>
<Component {...pageProps} />
</SessionProvider>
);
}
export default BloxStakes;
this is at /
is that correct?
im logged because i can access the dashboard idk how he knows
but even in private mode im logged ... ?
Hackberry nipple gall parasitoidOP
the secret can be 256 chard?
Hackberry nipple gall parasitoidOP
btw the login doesnt work..
nothing works ong
Hackberry nipple gall parasitoidOP
im gonna use discord how to setup it?
@Hackberry nipple gall parasitoid it's pretty hard to help you, without being inside your project and without the ability to test things own my own out. Either share your current project like it is on github or I can't help you for the reasons mentioned
@B33fb0n3 <@891245897659347004> it's pretty hard to help you, without being inside your project and without the ability to test things own my own out. Either share your current project like it is on github or I can't help you for the reasons mentioned
Hackberry nipple gall parasitoidOP
yes drop github its not a problem for me
○ Compiling /auth/login ...
✓ Compiled /auth/login in 2.4s
GET /auth/login 200 in 2777ms
GET /auth/login 200 in 97ms
GET /auth/login 200 in 103ms
GET /auth/login 200 in 96ms
GET /auth/login 200 in 97ms
GET /auth/login 200 in 90ms
GET /auth/login 200 in 91ms
GET /auth/login 200 in 89ms
GET /auth/login 200 in 90ms
GET /auth/login 200 in 91ms
GET /auth/login 200 in 86ms
GET /auth/login 200 in 87ms
GET /auth/login 200 in 84ms
GET /auth/login 200 in 82ms
GET /auth/login 200 in 77ms
✓ Compiled /auth/login in 2.4s
GET /auth/login 200 in 2777ms
GET /auth/login 200 in 97ms
GET /auth/login 200 in 103ms
GET /auth/login 200 in 96ms
GET /auth/login 200 in 97ms
GET /auth/login 200 in 90ms
GET /auth/login 200 in 91ms
GET /auth/login 200 in 89ms
GET /auth/login 200 in 90ms
GET /auth/login 200 in 91ms
GET /auth/login 200 in 86ms
GET /auth/login 200 in 87ms
GET /auth/login 200 in 84ms
GET /auth/login 200 in 82ms
GET /auth/login 200 in 77ms
i dont think this is normal btw
Hackberry nipple gall parasitoidOP
@B33fb0n3 can you give me your github user?, i lladd you
Hackberry nipple gall parasitoidOP
@B33fb0n3
@Hackberry nipple gall parasitoid <@301376057326567425> can you give me your github user?, i lladd you
others might want to help you as well, so make sure you share it with others as well
@B33fb0n3 others might want to help you as well, so make sure you share it with others as well
Hackberry nipple gall parasitoidOP
please check it up!
@Hackberry nipple gall parasitoid https://github.com/sdxqw/bloxstakes-web
Thanks for sharing! You middleware causes the problem. It redirects to often or removes somehow the CSS. Remove the redirects inside the middleware and you see, that it's working like expected
@Hackberry nipple gall parasitoid how so?
remove the redirects in the middleware and see yourself
@B33fb0n3 remove the redirects in the middleware and see yourself
Hackberry nipple gall parasitoidOP
which one haha
i cannot understand...
\
\
@Hackberry nipple gall parasitoid which one haha
there is only one haha xD
You can watch the page directly here: https://codesandbox.io/p/github/sdxqw/bloxstakes-web/csb-txgphf/draft/cool-tristan
You can watch the page directly here: https://codesandbox.io/p/github/sdxqw/bloxstakes-web/csb-txgphf/draft/cool-tristan
@B33fb0n3 there is only one haha xD
You can watch the page directly here: https://codesandbox.io/p/github/sdxqw/bloxstakes-web/csb-txgphf/draft/cool-tristan
Hackberry nipple gall parasitoidOP
so no redirect?
and log out?
so dashboard is public
ong this nextauth is getting me angry
@Hackberry nipple gall parasitoid so no redirect?
redirect is fine, when the user is not signed in yet, but not like you did
@B33fb0n3 redirect is fine, when the user is not signed in yet, but not like you did
Hackberry nipple gall parasitoidOP
how to do so?
like make it work
@Hackberry nipple gall parasitoid how to do so?
you need to change your matcher config. I changed your code a bit to make the redirect & middleware work correctly. See here: https://codesandbox.io/p/github/sdxqw/bloxstakes-web/csb-txgphf/draft/cool-tristan
@B33fb0n3 you need to change your matcher config. I changed your code a bit to make the redirect & middleware work correctly. See here: https://codesandbox.io/p/github/sdxqw/bloxstakes-web/csb-txgphf/draft/cool-tristan
Hackberry nipple gall parasitoidOP
quick question how to check if the session is working?
Your route.ts was also wrong:
const handler = NextAuth(authOptions);
-export const { GET, POST } = handler;
+export { handler as GET, handler as POST };
@B33fb0n3 Your route.ts was also wrong:
diff
const handler = NextAuth(authOptions);
-export const { GET, POST } = handler;
+export { handler as GET, handler as POST };
Hackberry nipple gall parasitoidOP
okay modified that too byt its doesnt get routed to dashboard
pathname: /dashboard
pathname: /auth/login
GET /auth/login 200 in 73ms
pathname: /dashboard
pathname: /auth/login
GET /auth/login 200 in 73ms
its not going on the second if
token is null
you also missed to configure your .env variables correctly
And you forgot to use the callbacks methods as well
And you forgot to use the callbacks methods as well
@B33fb0n3 you also missed to configure your .env variables correctly
And you forgot to use the callbacks methods as well
Hackberry nipple gall parasitoidOP
like>
You might want to start a new project and go step by step through the specific steps described on the next-auth website. I am telling you that, because when you don't know how you auth system works, then you can protect your page from attacks. And that not good
Hackberry nipple gall parasitoidOP
😦
I am sorry to tell you that. Without the understanding on what you are doing, it's senseless. Because I think that you integrating an auth system to protect your pages, but without knowing how everything works, your page is vulnable
Hackberry nipple gall parasitoidOP
isnt that auth.ts, the authorize method is used to check user and password?
middleware is that qhich checks for protected paths, so noone can access them until they are logged on
after thatn i dont know anything else
idk why the token is empty.. ?
@B33fb0n3 I am sorry to tell you that. Without the understanding on what you are doing, it's senseless. Because I think that you integrating an auth system to protect your pages, but without knowing how everything works, your page is vulnable
Hackberry nipple gall parasitoidOP
maybe with discord is easier?
as I got knowloadge of it
not sure how to do it as still next-auth is new to me
@B33fb0n3 I am sorry to tell you that. Without the understanding on what you are doing, it's senseless. Because I think that you integrating an auth system to protect your pages, but without knowing how everything works, your page is vulnable
Hackberry nipple gall parasitoidOP
Im trying to understand discord, and i got errors with oauth2 redirect_uri error
Hackberry nipple gall parasitoidOP
@B33fb0n3 can you delete that repository you have done?
i think i got it how to make it with discord as it way better and easier
Hackberry nipple gall parasitoidOP
which is the default i think
nut why it taking me here?
it should take me to auth/login
or im doing something wrong?
@B33fb0n3
nvm fixed
Hackberry nipple gall parasitoidOP
async signIn({profile}: { profile?: Profile }) {
return profile?.id === '891245897659347004';
}
return profile?.id === '891245897659347004';
}
its saying the id doesnt exists
im using discord
but in the console.log it printing id