Next.js — How to redirect all pages to HTTPS

Next.js — How to redirect all pages to HTTPS

If you wondered how to do this in just few lines of code, have a look at the “middleware” official documentation…

Next.js — How to redirect all pages to HTTPS

Photo by Nick Fewings on Unsplash

If you wondered how to do this in just few lines of code, have a look at the “middleware” official documentation https://nextjs.org/docs/middleware


You basically want to create a file in the pages folder called _middleware.ts, which gets called on every page!

Just copy the content below in /src/pages/_middleware.ts (or .js if you are not using TypeScript, and skip the NextRequest type)

This example has been taken from the repository of https://www.entitree.com which we highly recommend to have a look at to take inspiration for your project’s layout.

It’s not a good idea to redirect localhost to https so that’s why the code is redirecting only after the build command is run, as the framework will automatically set the NODE_ENV=production for us!

Happy Coding!

🥳

Leave a Reply