Password for site on enter
Unanswered
Borsoon posted this in #help-forum
BorsoonOP
I want to make it, so when you enter the site, you have to input a password. Also, I want to make it so if you try to access anything else than /password you are redirected back to the password page. I'm using a form and cookies.
This piece of code breaks everything (the css doesn't work and when I try to submit the password, it doesn't show any alert or anything, just removes the text from the placeholder and it seems to refresh). But when I remove it, everything works fine, but there is just no redirection.
The thing I'm trying to achieve is: If the user didn't input the password, keep redirecting him to the /password page, and make the /password page work
This piece of code breaks everything (the css doesn't work and when I try to submit the password, it doesn't show any alert or anything, just removes the text from the placeholder and it seems to refresh). But when I remove it, everything works fine, but there is just no redirection.
if (!authCookie && url.pathname !== '/password') {
url.pathname = '/password';
return NextResponse.redirect(url);
}The thing I'm trying to achieve is: If the user didn't input the password, keep redirecting him to the /password page, and make the /password page work
2 Replies
Sun bear
Hi, I would first adjust the middleware so that it matches the docs:
https://nextjs.org/docs/app/building-your-application/routing/middleware
And remove the useeffect import even if you dont need it.
And I would recommend to verify the password serverside and not with NEXT_PUBLIC clientside
Maybe think about using nextauth or create a serveraction
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url))
}https://nextjs.org/docs/app/building-your-application/routing/middleware
And remove the useeffect import even if you dont need it.
And I would recommend to verify the password serverside and not with NEXT_PUBLIC clientside
Maybe think about using nextauth or create a serveraction
Fieldfare
You probably dont even need an auth if its just a password you could work with middleware only and maybe something as simple as a usestate that is true when password is correct