DEV Community

Dika Mahendra
Dika Mahendra

Posted on • Updated on

How to Reverse Proxy NextJS with NGINX

Sup, let's get straight. Here's a simple tips to run your NextJS Pages (especially in dev environment, but also works on production ofc.) through Nginx. Before we started, I expect we're already have an Nginx configuration set up.

Then, we're just simply adds these configs:

# Proxy NextJS Chunks, exception and websocket for HMR
location ~ ^/_?_next.* {
        proxy_pass [YOUR_NEXTJS_HOST_HERE];
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
Enter fullscreen mode Exit fullscreen mode

Yeah. But why?
My case might be rare. I wanted to partially merge my NextJS Page into my existing website with different tech stacks (don't ask me why I didn't use NextJS at first start 🥲). So instead of embedding my NextJS page that dependent to my existing my website which takes lot of time to load, those /_next routes which loads JS chunks and another NextJS optimized stuffs could be passed directly into node server so it can reduce the latency.

But, it's just not about latency.
Previously, to debug my NextJS pages that merged, i have to compile every;single;changes; into production build to make it works. It's makes me frustrated because it's also waste my time since the hot reload and Webpack stuffs doesn't work due to 404 error etc. So, I tried to adds some reverse proxy to my config and that's it! Works like a charm.

If you have the same cases, hope it helps.

PS:
I would also thanks to Farid Inawan (psps.. Check his cool Instagram account here! He's making content about tech stuffs too) who helped me simplify the configuration. :)

Top comments (0)