Search code examples
node.jsnuxt.jsvercel

Unable to run API on non-root pages after Vercel deploy


I've been trying to deploy to a Nuxt app to Vercel. The app technically deploys, but only the main page will render. If I attempt to click through to a link that requires an API request, all the API requests on that page return with a 404 error. However, the same app will work perfectly fine on all pages on Localhost.

I'm not sure what's wrong with my deploy that is causing this. Here's what I currently have as my vercel.json

{
    "alias": "corey-lanier-blog",
    "name": "blog",
    "env": {
      "PORT": "4000",
      "SECRET": "@secret",
      "MONGODB_URI": "@mongodb_uri"
    },
    "version": 2,
    "builds": [
      {
        "src": "nuxt.config.js",
        "use": "@nuxtjs/vercel-builder",
        "config": {}
      }
    ],
    "routes": [
      {
        "src": "/api/posts/(.+)",
        "dest": "/api/posts.js"
      },
      {
        "src": "/api/users/(.+)",
        "dest": "/api/users.js"
      },
      {
        "src": "/api/comments/(.+)",
        "dest": "/api/comments.js"
      },
      {
        "src": "/(.*)",
        "dest": "/"
      }
    ]
  }

Unless the issue is that I've deployed my backend and the frontend on the same deploy and Nuxt is not allowing the subsequent API requests to go through. Is that possible? If so then why is it able to render the initial API requests for the front page render and not the subsequent ones on clickthroughs?


Solution

  • Nuxt deploys on Vercel overwrite the routes listed in your vercel.json. There is no clear way to prevent that within Nuxt or within the vercel.json. To solve this, you will need to split the codebase from being fullstack in one project/deploy, and redeploy the frontend/backend separate, as well as point your API routes within Nuxt to the URL for the backend. (You will also likely have to ensure CORS has been configured properly on your backend if you haven't already, so that you can accept requests from your frontend)