Matthew Kaye
Matthew Kaye

Reputation: 465

Nuxt server middleware with generate

I think i'm misunderstanding nuxt server middleware. I have an api directory with a single file that spins up express and writes records to a mysql database. Everything works as expected running in dev, but after nuxt generate, that endpoint always returns a 404.

Can you use nuxt generate with an internal API that runs on the server? I'd be using axios to hit this endpoint for what it's worth but I doubt that makes a difference.

from Nuxt config:

{
  target: static, 
  serverMiddleware: [{ path: '/api', handler: '~/api/index.js' }]
}

Upvotes: 1

Views: 2661

Answers (1)

Florian Pallas
Florian Pallas

Reputation: 582

Server middleware basically allows you to run your own code on the server nuxt spins up for you in target: 'server' mode. Therefore your approach won't work in static mode, as there is no server running your middleware. You are only serving static files. In dev mode you are running a server locally, which is why your middleware works fine there.

For it to work in production you have two options:

  • Run nuxt in target: 'server' mode, instead of generating static files
  • Spin up your express server separately, instead of using server middleware in nuxt

I hope you understand how server middleware works now and you can make the right decision for your project!

Upvotes: 0

Related Questions