DEV Community

Cover image for Setting up proxy in Next.js for DEV environment
Georgekutty Antony
Georgekutty Antony

Posted on

Setting up proxy in Next.js for DEV environment

Introduction

In general, we expect to have a default proxy setup in Next.js just like react. But unfortunately, there is no such feature in package.json and we need to add custom proxy server and hacks to work with the external API in the development environment. Fortunately, in version 9.5, Next.js released a new simple way to interact with APIs that hosted outside the app.

Lets start by modifying our next.config.js file.

Step 1

We can use the new rule "rewrites". Refer to the documentation for the same. In order to proxy our API requests, we need to add this rewrites rule with source and destination. Please have a look at the below code.

 async rewrites() {
      [
          {
            source: '/api/:slug*',
            destination: `http://localhost:3333/api/:slug*`,
          },
        ]
 }
Enter fullscreen mode Exit fullscreen mode

Here, the source will filter every calls that start with '/api' and the destination will be used to rewrite the request with 'http://localhost:3333/api'. The :slug* will take the remaining part and append the same to destination url.

Step 2

If we need to add another location that hosted separately, for example, every calls that starts with '/images', we can simply add the following code to our existing rewrites rule.

async rewrites() {
      [
          {
            source: '/api/:slug*',
            destination: `http://localhost:3333/api/:slug*`,
          },
          {
            source: '/images/:slug*',
            destination: `http://localhost:3334/images/:slug*`,
          }
      ]
 }
Enter fullscreen mode Exit fullscreen mode

Here, the new rule source will filter every calls that start with '/images' and the destination will be used to rewrite the request with 'http://localhost:3334/images'. As I have mentioned earlier, the :slug* will take the remaining part and append the same to destination url.

Step 3

Furthermore, the rules we have added will work in production as well. If we have dedicated reverse proxy in production, then we don't require this rule. Whereas, we can disable it in production by adding a check for NODE_ENV.

async rewrites() {
      return !process.env.NODE_ENV === 'production'
      ? [
          {
            source: '/api/:slug*',
            destination: `http://localhost:3333/api/:slug*`,
          },
          {
            source: '/images/:slug*',
            destination: `http://localhost:3333/images/:slug*`,
          },
        ]
      : [];
 }
Enter fullscreen mode Exit fullscreen mode
Please don't forget to run set NODE_ENV before running the npm run build command.

Step 4

Last step is to ensure that all our existing APIs in the client side has been changed to relative url. If we have API calls that needs to be run in server, then we need to change the external url to Next.js local development url just like in the following code.


export const getStaticProps/getServerSideProps = async () => {

  // Before Setting Proxy
  // const data = await getData('http://localhost:3333/api/data');

  // After Setting Proxy
  const data = await getData('http://localhost:3000/api/data');

  return {
    props: {
      data
    },
  };
};

Enter fullscreen mode Exit fullscreen mode

Here, Next.js will rewrite the http://localhost:3000/api to http://localhost:3333/api using the rewrites rule we have specified earlier in the next.config.js.

Conclusion

In this article, we saw that how we can set up proxy to external APIs without installing any third party packages or using custom server.js. I recommend you to have look at the Next.js documentation!

Top comments (9)

Collapse
 
anishprvn profile image
Anish Praveen

Useful article. Proper code snippets are given.

Collapse
 
dalalrohit profile image
Rohit Dalal

Great article, thank you so much!

Collapse
 
dalalrohit profile image
Rohit Dalal

Hey,
Can I use this feature with next-compose-plugins ?
Wanted to use multiple pluings like withSass, withImages along with it.

Thank you

Collapse
 
george3447 profile image
Georgekutty Antony • Edited

Absolutely, some thing like the following should work.

const withPlugins = require('next-compose-plugins');
const sass = require('@zeit/next-sass');

module.exports = withPlugins([
  [sass],
], {
  async rewrites() {
      return !process.env.NODE_ENV === 'production'
      ? [
          {
            source: '/api/:slug*',
            destination: `http://localhost:3333/api/:slug*`,
          },
          {
            source: '/images/:slug*',
            destination: `http://localhost:3333/images/:slug*`,
          },
        ]
      : [];
   }
});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
2manoj1 profile image
Manoj Mukherjee

Is it possible authorization header set in proxy? We need set header on server not from client.

Collapse
 
frankbab profile image
Frank Baby

Nice article 👍

Collapse
 
guilleflm profile image
Guillermo Lopez

Hey, great article!
You know, often when you proxy to an API you need to include some Authorization header. Is that possible with this approach?
Like modify req object before the overwrites occour?

Collapse
 
marnixhoh profile image
marnixhoh

Any luck with getting this to work with sockets? In particular socket.io?

Collapse
 
phd147 profile image
Phan Huỳnh Đức

hi, i have a question for you, i want to proxy in http request called by client side, do you have the solution ?