node.jsflasknext.js

Use both Flask/Python API route and NodeJS API route with pages router


I'm using a Python Flask API backend with my Next app according to this article.

I'm using Next 12.3.4 (pages router).

The structure of my API is currently:

pages
--|api
----|__pycache__
----|index.py

next.config.js:

  async rewrites()
  {
      return [
          {
              source: '/api/:path*',
              destination:
              process.env.NODE_ENV === 'development'
                  ? 'http://127.0.0.1:8000/api/:path*'
                  : '/api/',
          }
      ]
  },

I want to add a new Node API route under the pages/api/ folder, that I would be able to hit separately from the Python/Flask route.

For example, await axios.post('/api/newNodeRoute').

Right now if I try this, I get a 404 error as it all seems to be going through my Python/Flask route. I've used Next API routes many times before, but never while combined with a Python/Flask backend, so I'm not sure how to handle this.


Solution

  • You could put your python endpoints in a py folder and only rewrite for /py endpoints, I think others will default to the next.js node server.

    async rewrites()
      {
          return [
              {
                  source: '/api/py/:path*',
                  destination:
                  process.env.NODE_ENV === 'development'
                      ? 'http://127.0.0.1:8000/api/:path*'
                      : '/api/py/:path*',
              }
          ]
      }