How to use Nodejs as Backend in your Nuxtjs App: A Beginner Tutorial

How to use Nodejs as Backend in your Nuxtjs App: A Beginner Tutorial

Node.js is a server-side JavaScript runtime environment, while Nuxt.js is a framework for building universal Vue.js applications. Nuxt.js is built on top of Node.js, so Node.js is already integrated into Nuxt.js.

When you create a new Nuxt.js project, you can use Node.js in your project by default. You can use Node.js to write server-side code, to handle API requests, or to interact with databases. I'll walk you through the steps of using Node.js with your Nuxt.js app with code examples.

Here is an example of a full Nuxt.js code with Node.js that creates a simple blog application. The blog posts are stored in a MongoDB database, and we'll use Node.js to create an API to access the blog post data.

Prequsites: Internet Connection, Text Editor e.g VS Code, Sublime Text etc.,

Sure, here are the steps to install Nuxt.js:

  1. Install Node.js on your computer if you haven't already. You can download it from the official Node.js website

  2. Open a terminal or command prompt and create a new directory for your Nuxt.js projects:

    mkdir nuxt-folder

    cd nuxt-folder

  3. Create a new Nuxt.js project with the create-nuxt-app command:

    npx create-nuxt-app my-blog-app

  4. Add the MongoDB and Mongoose packages to your project.:

    npm install nuxt

  5. Create a new directory called pages in your project directory:

    npm install mongodb mongoose

  6. Create a new MongoDB database and collection to store the blog posts. You can use another database server you like but if you are interested in MongoDB you can visit the MongoDB official documentation for more information.

  7. Create a new Node.js file named server.js in the root of your project. This file will contain the server-side code that provides an API to access the blog posts.

     // server.js
    
     const express = require('express')
     const bodyParser = require('body-parser')
     const mongoose = require('mongoose')
    
     const app = express()
    
     app.use(bodyParser.json())
    
     mongoose.connect('mongodb://localhost:27017/my-blog-db', { useNewUrlParser: true })
    
     const Post = mongoose.model('Post', {
       title: String,
       content: String
     })
    
     app.get('/api/posts', (req, res) => {
       Post.find((err, posts) => {
         if (err) {
           res.send(err)
         } else {
           res.json(posts)
         }
       })
     })
    
     app.post('/api/posts', (req, res) => {
       const post = new Post(req.body)
    
       post.save((err) => {
         if (err) {
           res.send(err)
         } else {
           res.send('Post saved')
         }
       })
     })
    
     app.listen(3000, () => {
       console.log('Server listening on port 3000')
     })
    

    In this example, we're using the express module to create a simple server that listens on port 3000. We've created two endpoints: /api/posts to get all the blog posts and to create a new blog post.

  8. Update the Nuxt.js configuration to use the Node.js server. Open the nuxt.config.js file and add the following code:

     // nuxt.config.js
    
     module.exports = {
       serverMiddleware: [
         { path: '/api', handler: '~/server.js' }
       ]
     }
    
  9. Create a new Nuxt.js component named Blog.vue in the pages directory of your project. This component will display a list of blog posts and allow the user to create a new blog post.

     // pages/Blog.vue
    
     <template>
       <div>
         <h1>Blog</h1>
         <form @submit.prevent="submitPost">
           <div>
             <label>Title:</label>
             <input v-model="title">
           </div>
           <div>
             <label>Content:</label>
             <textarea v-model="content"></textarea>
           </div>
           <div>
             <button type="submit">Create Post</button>
           </div>
         </form>
         <ul>
           <li v-for="post in posts" :key="post.id">
             <h2>{{ post.title }}</h2>
             <p>{{ post.content }}</p>
           </li>
         </ul>
       </div>
     </template>
    
     <script>
     export default {
       data() {
         return {
           title: '',
           content: '',
           posts: []
         }
       },
    
       async fetch() {
         const { data } = await this.$axios.get('/api/posts')
         this.posts = data
       },
    
       methods: {
         async submitPost() {
           await this.$axios.post('/api/posts', { 
                title: this.title,
                content: this.content 
              }) 
           this.title = ''
           this.content = ''
           const { data } = await this.$axios.get('/api/posts')
           this.posts = data
         }
      };
     </script>
    

    In this example, we're using the fetch method to retrieve the list of blog posts from the API and display them on the page. We're also using the $axios module to send a POST request to the API when the user creates a new blog post.

  10. Run the project with the following command:

    npm run dev

    This will start the Nuxt.js development server and the Node.js API server. You can access the blog by going to http://localhost:3000/blog. That's it! You now have a simple blog application that uses Node.js and MongoDB to store and retrieve blog post data.

  11. Finally, start the development server by running the following command:

    npm run dev

    This will start the server and make your app available at http://localhost:3000.

With this steps, you now have sufficient knowledge of how to create your nuxt app using nodejs as backend. It is easier using nodejs as backend for nuxt app because its build on top of it and its easier to ship to production. It can also be use for server side rendering. I will write about that in future article.

Thank you for reading this tutorial. please like and share.