Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Doesn't work with App Router #83

Open
billsbooth opened this issue Dec 11, 2023 · 2 comments
Open

Doesn't work with App Router #83

billsbooth opened this issue Dec 11, 2023 · 2 comments

Comments

@billsbooth
Copy link

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

@Jamedjo
Copy link

Jamedjo commented Feb 23, 2024

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",
});

@lamngo255
Copy link

lamngo255 commented Aug 8, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants