Password protect your Next.js projects.
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.
Set Global Variable: Add process.env.PASSWORD_PROTECT
in next.config.js.
process.env.PASSWORD_PROTECT = 'true';
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';
Integrate HOC: Add the withPasswordProtect
HOC to the default export of App in pages/_app.tsx.
export default withPasswordProtect(App, { checkApiUrl, loginApiUrl });
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.