node.jsvue.jsnuxt.jsfly

How to add server-side database access to Nuxt app on Fly.io


I am trying to get started with Fly.io. I know Vue well and wanted to try Nuxt and Node.js. I cannot seem to figure out how to add server-side components and classes for handling AJAX requests.

I followed the official tutorial https://fly.io/docs/languages-and-frameworks/nuxtjs/

npm init nuxt-app@latest spec-land

create-nuxt-app v5.0.0
✨  Generating Nuxt.js project in spec-land
? Project name: spec-land
? Programming language: JavaScript
? Package manager: Npm
? UI framework: Element
? Template engine: HTML
? Nuxt.js modules: Axios - Promise based HTTP client
? Linting tools: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Testing framework: None
? Rendering mode: Single Page App
? Deployment target: Server (Node.js hosting)
? Development tools: jsconfig.json (Recommended for VS Code if you're not using typescript)
? What is your GitHub username? --
? Version control system: Git

🎉  Successfully created project spec-land

$ touch pages/index.js
$ npm run dev

After adding some front-end code, is this generated project equipped to run JavaScript on the server in the same fly.io deploy?


Solution

  • For a Nuxt2 app, you need to have Rendering Mode as Universal (SSR/SSG) or ssr: true in your nuxt.config.js file, otherwise, you will not have an isomorphic app.

    Nuxt will run some code on the server side + client side (isomorphic), while some will be run only on the client side only.

    The setup to have a serverMiddleware for Nuxt2 is as follows. Quite tricky and not working so well.
    Nuxt3 handles that pretty well on the opposite side.

    Overall, Nuxt2 does have some capabilities regarding server-side code but is not as flexible as Nuxt3. Tbh, if you want to use Nuxt2, I would recommend not trying to set up an actual database linked to it, but rather accessing it remotely via axios or like.