Experience the power of SSR Nuxt.js with a seamlessly integrated REST API backend

Currently, I am working on developing a SSR Nuxt.js application that integrates with a REST API server.

In order to achieve this, I have included my endpoint /api into the Nuxt server.js code as shown below:

const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')

const app = express()

// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = process.env.NODE_ENV !== 'production'

// MY REST API ENDPOINT (Is this the correct approach?)
const routesApi = require('./api/routes')
app.use('/api', routesApi)

async function start() {
  // Initialize Nuxt.js
  const nuxt = new Nuxt(config)

  const { host, port } = nuxt.options.server

  await nuxt.ready()
  // Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  // Provide nuxt middleware to express
  app.use(nuxt.render)

  // Start listening on the server
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}
start()

I have not come across any examples related to this specific method.

I would appreciate some guidance to confirm if this is the correct approach.

Thank you for your assistance.

Answer №1

If you're interested, check out this article: It provides some insights on tackling the "API with Nuxt" scenario.

Your approach seems sufficient for a small integrated API, as it helps avoid dealing with CORS issues by setting up a proxy. You can enhance it further using serverMiddleware:

// nuxt.config.js
export default {
...
  serverMiddleware: [
    '/api': '~/api/index.js'
  ],
...
// api/index.js
export default function (req, res, next) {
  ... // Nothing to see here
  next()
}

However, for larger APIs, hosting them on a separate server is recommended for scalability and separation of concerns. While Nuxt excels in universal app rendering middleware, the API can be written in a different language or backend. To address CORS issues, ensure that your /api is on the same domain as intended; using the Nuxt proxy-module can simplify this process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to cycle through arrays containing objects using Vue

Within my array list, each group contains different objects. My goal is to iterate through each group and verify if any object in a list meets a specific condition. Although I attempted to achieve this, my current code falls short of iterating through eve ...

Issues arising with transferring information between components

My webpage had a header with a search engine input, a list of posts, and pagination all on one page. I made the decision to separate the header into its own component in a different Vue file. However, after making this change, searching for posts by their ...

A more intelligent approach for generating JSON responses using Mysql

Here is the code I have on my server side using Node.js: var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'SOMEUSER', password: 'SOMEPASSWD', database: 'SOMED ...

Potential Unresolved Promise Rejection in React Native

When attempting to run the application, I encountered an issue where the server was not working and Node.js displayed an error message. I am unable to determine the cause of this error. Can anyone please assist me in resolving this issue? As a newcomer t ...

Unleashing the full power of Node.JS asynchronous operations

I've been struggling to grasp how to effectively manage the asynchronous nature of Node.JS. Despite reading extensively on the topic and experimenting with message passing and callback functions, I can't seem to get my object constructor to load ...

Is it possible to conceal or encrypt JSON data or header information in HTTP requests and calls?

I am currently developing a full stack website with Flask, Vuejs and SQLite3. I have been using axios to make backend calls from the frontend. However, I noticed that when I make 'GET' requests using axios (Vuejs) to the backend on a particular r ...

Managing DOM elements within a Vue 3 template using Typescript

As I delve into the world of Vue 3 as a beginner, I encountered a challenge when it came to managing the DOM within Vue 3 templates. Let's take a look at the source code. MainContainer.vue <template> <div class="main-container" r ...

When loading a page with Puppeteer using the setContent method, images may not be loaded

Currently, I am experiencing an issue with Puppeteer where it does not load resources that are specified with relative paths (such as background.png in the image src or in CSS url()). When I try to load the content of a local file using setContent(), the o ...

The configuration settings for Express are not functioning properly

Initially, I utilized the following code: app.configure( function(){ app.use(express.static(__dirname, '/')); }); Later, I realized that it was an outdated version. So, I switched to: var env = process.env.NODE_ENV || 'development&apo ...

Tips for accessing user-defined headers within CORS middleware

I've developed a CORS middleware utilizing the CORS package. This middleware is invoked before each request. Here's how I implemented it: const corsMiddleware = async (req, callback) => { const { userid } = req.headers|| req.cookies {}; l ...

Deploy Node.js on a Debian server hosted on Google Compute Engine

Currently, I am operating a Debian server on Google Compute Engine using a host called example.com. My goal is to run a node.js app within a specific directory on this server, for instance, example.com/mynodeapp. Fortunately, the necessary components such ...

Streamlining the Compilation of Dependencies for Electron Application Distribution

I am currently exploring the best method to package and distribute various dependencies (such as node modules and client-side scripts/frameworks like Angular) with my Electron App. While the standard approach of npm install module-name --save is effective ...

Troubleshooting an npm peerDependency problem between grunt and flatiron peers

While initially writing this question, I managed to solve the issue on my own. However, I will still share both the problem and solution here in case it can benefit someone else. Additionally, if anyone has insights on the reasoning behind what occurred, I ...

Get the png image file and display a preview of it

Within my template, I have an img tag that is linked to a state known as "imageBuffer" <img v-bind:src="imageBuffer" alt="" /> In the logic of the page, there are two file inputs and I've utilized a single function to manag ...

Can an express middleware be implemented for a particular HTTP request method?

I am looking to incorporate an Express middleware that will be activated whenever a POST request is made, regardless of the route URL. I believe the following code snippet should achieve this: app.use(function (req, res, next) { if (req.method === &ap ...

Is there a way to update all scoped packages to a specific tagged version at once?

Is there a method to upgrade all scoped packages to a specific tag other than latest? For example, let's say I have multiple packages under the scope @scope, such as @scope/pkg1, @scope/pkg2, and so on. These packages have tags like stable. Is it pos ...

Deploying a pair of GitHub repositories to a unified Azure web application

Although this isn't exactly a technical question, I couldn't find a more appropriate stackexchange site for it. Recently, I made the move to Azure for deploying my backend web applications and APIs. I discovered that it's possible to deploy ...

React to the Vue: Only activate the event if the key is pressed twice consecutively

In my application, I am creating a unique feature where users can trigger a window to appear by inputting the symbol @ (shift + 50). This will allow them to access predefined variables... <textarea @keyup.shift.50="showWindow"></textarea> My ...

Making changes to the Node.js version in a Dockerfile causes issues with installing dependencies

I recently updated the Node.js base image in my Dockerfile from 12.14.1 to 16.14.2, and now I'm encountering issues when trying to build an image with my Dockerfile. I have confirmed that there are no deprecated or removed dependencies being used. T ...

There was an error encountered while using the findOneAndRemove() method: TypeError - it was unable to read the property '_id' of an

I encountered an error 'TypeError: Cannot read property '_id' of undefined' when using the findOneAndRemove() function with the required parameters in MongoDB, even though my database has the attribute '_id'. Interestingly, w ...