next-password-protect
next-password-protect copied to clipboard
Doesn't work with App Router
Next.js updated their routing to app router which is not compatible with this version.
Rough outline of what I've used to get this working:
src/app/layout.tsx
checkAuthenticated
import { cookies } from 'next/headers'
import jwt from 'jsonwebtoken'
import { password } from "../consts"
async function checkAuthenticated(cookieName = 'next-password-protect'): Promise<boolean> {
try {
const authCookie = cookies().get(cookieName)
if(!authCookie) {
return false
}
/* NOTE: It's not usual to use the password as JWT secret, but since you already
* have access to the environment when you know the password, in this specific
* use case it doesn't add any value for an intruder if the secret is known.
*/
jwt.verify(authCookie.value, password);
return true
} catch (e) {
return false
}
}
export default async function RootLayout
const authenticated = await checkAuthenticated()
if (!authenticated) {
return (<html><body><Login/></body></html>)
}
src/app/components/login/index.tsx
'use client';
import { LoginComponent } from 'next-password-protect/dist/esm/src/hoc/LoginComponent';
export default LoginComponent;
src/pages/api/login.ts
import { loginHandler } from "next-password-protect";
import { password } from "../../consts"
export default loginHandler(password, {
cookieName: "next-password-protect",
});
@Jamedjo Awesome, thank you! I think we can save the password in .env.local file so that nosy people can't inspect the source code too 😄
// .env.local
NEXT_PUBLIC_PASSWORD_PROTECT=1234
Hope the maintainer can work on the official update for App Router soon, this is the best workaround for now.