Fabian Bosler
Fabian Bosler

Reputation: 2510

How to use proxy in package.json in next.js?

In create-react-app(s) it is possible to specify a proxy in the package.json like this:

{
    "name": "client",
    "version": "0.1.0",
    "private": true,
>>> "proxy": "http://localhost:5000", <<<
    "dependencies": {
            ...
    },
    "scripts": {
            ...
    },
    "eslintConfig": {
            ...
    },
    "browserslist": {
        "production": [
            ...
        ],
        "development": [
            ...
        ]
    }
}

Doing the same in a next.js app has no effect whatsoever. Is there a workaround? This would be especially useful when starting to decommission an old front-end but still using the backend.

Upvotes: 2

Views: 8818

Answers (2)

greensuisse
greensuisse

Reputation: 1827

Another way is to use rewrites config: https://nextjs.org/docs/api-reference/next.config.js/rewrites

module.exports = {
    async rewrites() {
        return [
            {
                source: '/api/:slug*',
                destination: 'http://www.example.com/api/:slug*'
            },
        ]
    },
}

Upvotes: 2

Denys Levshenkov
Denys Levshenkov

Reputation: 284

Try to use this package from npm to create a Node.js proxy for Express: http-proxy-middleware

Then You can configure the target option to proxy requests to the correct domain:

const proxy = require('http-proxy-middleware')

app.use('/api', proxy({ target: 'http://localhost:5000', changeOrigin: true }));

Find similar package for next.js here: next-http-proxy-middleware

Upvotes: 2

Related Questions