Lead

The DAO community allow the community to decide what determines a valuable contribution and where resources should be directed to ensure proper incentives and rewards for various types of…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Easily Password Protect NextJS pages with Iron Session

Create a .env.local and .env.local.example file at the root of your project. Make sure.env.local is added to your .gitignore (it should be by default in a vanilla NextJS setup) This file will look like this:

Create a password 32 characters long for the SECRET (you will not need to remember this), then create a password you can remember for PASSWORD (this is what you’ll enter on the page to access your secure route).

You will then create a few new files:

/utils/session.js

/pages/api/login.js

/pages/api/logout.js

/pages/api/user.js

/utils/useUser.js

/pages/login.jsx

These pages and API routes create the backbone to log in and log out, and a form page you can enter your password on. You can see the login API route is doing a simple comparison of the password in the request with the password you set in your ENV file.

The last thing you need is the route (or routes) you want to secure. The example here does it with server side props (SSR) but you could also call the api route from the client side. This will redirect to /login if the user is not returned from the withSessionSsr handler or show the page if you are logged in.

pages/admin.js

Encrypted cookies are pretty awesome and the people behind `iron-session` are insanely smart. This will get you a simple and functional secure page that you can access with your password. You are vulnerable to brute force here just as an FYI. You'll have to do something else to mitigate that but if you name your pages something other than login and admin, you can at least be a bit obscure and get slight security through that.

Don’t forget to add the two ENV vars to your server as well when you deploy.

Let me know if you have questions or suggested modifications by contacting me on twitter @itwasmattgregg.

Add a comment

Related posts:

29 Life Lessons on My 29th Birthday

Today I turn 29 years old. Still relatively young in ultimate lifespan, but enough to think that I’ve learned some things. Every year on my birthday, I do two things. First, I write down all of my…

A Decentralized Social Trading

Numerous practical and simple-to-use trading instruments for decentralized finance (DeFi) are included in the DeXe crypto ecosystem. Along with offering cutting-edge trading technology, the…

He Took Another Condom From His Right Pocket

We were in what I thought was his apartment, “what’s next?” he asked, taking out a condom from his left pocket. “Certainly nothing that will involve this condom,” I replied. “It’s banana flavored…