next-password-protect icon indicating copy to clipboard operation
next-password-protect copied to clipboard

Doesn't work with App Router

Open billsbooth opened this issue 1 year ago • 2 comments

Next.js updated their routing to app router which is not compatible with this version.

billsbooth avatar Dec 11 '23 20:12 billsbooth

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 avatar Feb 23 '24 19:02 Jamedjo

@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.

lamngo255 avatar Aug 08 '24 06:08 lamngo255