2

I have builded an app using Nuxt and I have created simply server middleware for handling email sending. Everything is working on dev but on production I have 404 error from that endpoint. Does anybody know how to include server-middleware into build files or any other way?

server-middleware:

const bodyParser = require('body-parser')
const app = require('express')()

app.use(bodyParser.json())

app.post('/', (req, res) => {
// Some code here
})

module.exports = app

Nuxt.config.js

serverMiddleware: [
    { path: '/contact/send', handler: '~/server-middleware/email.js' }
  ],

Response here: enter image description here

Freestyle09
  • 4,894
  • 8
  • 52
  • 83
  • Do you use your app as static only or with SSR too ? – kissu Apr 15 '21 at 16:54
  • I builded my app with SSR – Freestyle09 Apr 15 '21 at 16:57
  • Looks fine to me. Didn't you forget any env variable or alike ? I mean, are you sure the issue is coming from here ? Also, are your packages used in the middleware installed as `dependencies` and not just `devDependecies` ? – kissu Apr 15 '21 at 17:02
  • 1
    Yeah I don't see any string 'contact/send' in build folder :/ I can see that this is no existing in build folder is not builded up :/ I am getting 404 which is correct because it is not there :/ – Freestyle09 Apr 15 '21 at 17:21
  • Where is your app hosted btw? Are you sure it do have a node server for SSR available? – kissu Apr 16 '21 at 00:12
  • Yeah, I host on mydevil.net and I know everything is ok, but I got an answer elsewhere https://github.com/nuxt/nuxt.js/issues/9158#issuecomment-820676790 – Freestyle09 Apr 16 '21 at 08:02

2 Answers2

2

I found an answer on github issue nuxt repo:

This is correct - server middleware aren't compiled or part of your webpack build and so you should make sure to copy them separately into production. (As well as making sure that any dependencies they have are installed in production.)

(Note that this will change with Nuxt 3 - you'll be able to have a single built server that includes your server middleware.)

Issue here: https://github.com/nuxt/nuxt.js/issues/9158#issuecomment-820676790

Freestyle09
  • 4,894
  • 8
  • 52
  • 83
0

Here is an in-depth answer regarding the whole setup of a serverMiddleware.


This solutions seems to work: https://github.com/nuxt/nuxt.js/issues/1486#issuecomment-325181524

// nuxt.config.js
serverMiddleware: [
  '~/api/index.js',
]
// api/index.js
const app = require('express')()
module.exports = { path: '/api', handler: app }

app.get('/say/:word', (req, res) => {
  res.json(req.params)
})
kissu
  • 40,416
  • 14
  • 65
  • 133