Next Password Protect screenshot

Next Password Protect

Author Avatar Theme by Instantcommerce
Updated: 7 Sep 2022
322 Stars

Password protect your Next.js projects.

Categories

Overview:

The Next.js Password Protect library adds a password prompt to a Next.js deployment, consisting of two serverless API routes for login and password validation, along with a Higher-Order Component (HOC) that authenticates logged-in users. This tool is designed for staging or preview environments to restrict unauthorized access, not for robust password security.

Features:

  • Password Prompt: Adds a password prompt to Next.js deployments.
  • Serverless API Routes: Includes login route for password verification and setting JWT cookie, and check route for validating JWT cookie.
  • HOC Integration: Wraps Next.js App with a Higher-Order Component for user authentication.
  • Environment Variable Setup: Enables dead code elimination using process.env.PASSWORD_PROTECT.
  • Customizable Options: Options for cookie settings, API routes, and login prompt component customization.

Installation:

  1. Set Global Variable: Add process.env.PASSWORD_PROTECT in next.config.js.

    process.env.PASSWORD_PROTECT = 'true';
    
  2. Add API Routes: Create login and password check API routes, and specify their paths in the configuration.

    export const loginApiUrl = '/api/login';
    export const checkApiUrl = '/api/passwordCheck';
    
  3. Integrate HOC: Add the withPasswordProtect HOC to the default export of App in pages/_app.tsx.

    export default withPasswordProtect(App, { checkApiUrl, loginApiUrl });
    

Summary:

The Next.js Password Protect library provides a simple way to add a password prompt for restricting access to staging or preview environments. By setting environment variables, adding API routes, and integrating the HOC, users can enhance security without bloating the production bundle size. This tool is best suited for keeping unauthorized users out, rather than as a full-fledged password authentication solution.