0

I need to create a simple route /my-route that returns a JSON { "ok": true }. If possible, this route should be available only from the server.

I found a documentation but with Nuxt3 only, and Nuxt3 is not released yet.

Anyone knows how to do that with Nuxt 2?

Paleo
  • 21,831
  • 4
  • 65
  • 76
  • Nuxt3 is released and already available. For Nuxt2, give a read to this one: https://stackoverflow.com/a/72102209/8816585 – kissu May 11 '22 at 13:47
  • Also, the `this route should be available only from the server` part is basically saying that you want to create an endpoint which is only accessible from another backend? What's the idea with that? – kissu May 11 '22 at 13:49
  • @kissu No, it means that this route will not be used or even accessible from the rest of the front. No need to serve an HTML with the bundled JS etc. It is just a healthcheck that says to the monitoring system that yes the Nuxt server is alive. – Paleo May 11 '22 at 15:32
  • So, you do have it as SSR? Why not pinging a simple `/healthcheck` page? Either it's served or not. – kissu May 11 '22 at 15:45
  • 1
    @kissu Because `@nuxtjs/i18n` is terribly stubborn and it insists on putting back a language prefix. But I just found a solution. Thanks anyway. :-) – Paleo May 11 '22 at 18:08
  • You can always remove the prefix if it is annoying you. Also, I'm pretty sure you can have a route that is not i18n'ed. – kissu May 11 '22 at 18:10

1 Answers1

1

Found it! In nuxt.config.js, add a server middleware:

serverMiddleware: [
  {
    path: '/my-route',
    handler: (_req, res) => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.write(JSON.stringify({ ok: true }))
      res.end();
    }
  },
],
kissu
  • 40,416
  • 14
  • 65
  • 133
Paleo
  • 21,831
  • 4
  • 65
  • 76