Using Serverless Functions with Nuxt.js

Using Serverless Functions with Nuxt.js

In this Nuxt.js tutorial, we explore serverless by building a static app with Nuxt.js and setting up the API endpoint with Netlify Functions.

In this tutorial, we explore serverless by building a static app with Nuxt.js and setting up the API endpoint with Netlify Functions.

There has been a continuous shift in the way frontend developers build web applications. Nowadays, you don’t need to know about managing servers to build and ship an application. That’s what serverless is all about.

Let’s say you’re building a contact form on your portfolio site. Typically, you would want your visitors to send you an email when they’re interested in your services. You might want to write an API that connects to your preferred mail service provider and then spin up a server to run your API.

Is there anything wrong with this approach? No. However, a server works 24/7 and it’s always prepared for requests. For a portfolio site contact form, this approach is cost-ineffective and a waste of server resources. A use case like this is where serverless really comes in handy.

What does serverless mean?

Serverless doesn’t mean there’s no server; it just means you’re using a third-party service, such as AWS, to manage and set up servers so you only have to provide autonomous functions. These are popularly called serverless functions. This way, your serverless “server” is only spun whenever there’s a request and you’re only charged for the resources used during that period.

Serverless functions in Nuxt.js

To show how serverless functions work, we’ll build a contact form with Nuxt.js and Netlify Functions. A demo of the complete application is available here.

To follow along with this tutorial, you’ll need the following.

  • Experience working with Vue.js and Nuxt.js
  • A Netlify account
  • A Mailgun account

Setting up a Nuxt.js project

Let’s start by creating a new Nuxt.js application. To style the app, we’ll use Chakra UI, a simple modular and accessible component library that provides the building blocks to build Vue.js applications with speed.

yarn create nuxt-app serverless-contact-form

When prompted for a UI framework, select Chakra UI. For Nuxt.js modules, select Axios.

Once that’s done, start the application.

cd serverless-contact-form
yarn dev

For the rest of the tutorial, we’ll assume the app is running.

Creating a contact form

To keep things simple and straightforward, we’ll place the contact form directly on the home page. So let’s update the index.vue file inside the pages directory.

Start by updating the template section, as shown below.

// pages/index.vue

<template>
  <div class="container">
    <CBox
      v-bind="mainStyles[colorMode]"
      d="flex"
      w="100vw"
      h="100vh"
      flex-dir="column"
      justify-content="center"
    >
      <CHeading text-align="center" mb="4">
        Serverless contact form
      </CHeading>

      <CFlex justify="center" direction="column" align="center">
        <CBox mb="3">
          <CIconButton
            mr="3"
            :icon="colorMode === 'light' ? 'moon' : 'sun'"
            :aria-label="`Switch to ${
              colorMode === 'light' ? 'dark' : 'light'
            } mode`"
            @click="toggleColorMode"
          />
        </CBox>

        <CBox text-align="left" width="50%">
          <form @submit.prevent="sendContactToLambdaFunction">
            <CFormControl>
              <CFormLabel for="name">
                Name
              </CFormLabel>
              <CInput id="name" v-model="form.name" type="text" aria-describedby="name" />
            </CFormControl>

            <CFormControl>
              <CFormLabel for="email">
                Email
              </CFormLabel>
              <CInput id="email" v-model="form.email" type="email" aria-describedby="email-helper-text" />
              <CFormHelperText id="email-helper-text">
                We'll never share your email.
              </CFormHelperText>
            </CFormControl>

            <CFormControl>
              <CFormLabel for="message">
                Message
              </CFormLabel>
              <CTextarea v-model="form.message" placeholder="Type your message" />
            </CFormControl>

            <CBox mt="12" d="flex" flex-dir="column" align="center">
              <CButton type="submit" right-icon="arrow-forward" width="20%" variant-color="vue" variant="outline">
                Submit
              </CButton>
            </CBox>
          </form>
        </CBox>
      </CFlex>
    </CBox>
  </div>
</template>

The contact form contains three fields: name, email, and message. Once the form is submitted, a sendContactToLambdaFunction(), which handles sending the message, is called.

Let’s update the script section as well.

// pages/index.vue

<script lang="js">
  import {
    CBox,
    CButton,
    CIconButton,
    CFlex,
    CHeading,
    CTextarea,
    CFormControl,
    CFormLabel,
    CInput,
    CFormHelperText
  } from '@chakra-ui/vue'

export default {
  name: 'App',
  inject: ['$chakraColorMode', '$toggleColorMode'],
  components: {
    CBox,
    CButton,
    CIconButton,
    CFlex,
    CHeading,
    CTextarea,
    CFormControl,
    CFormLabel,
    CInput,
    CFormHelperText
  },
  data () {
    return {
      mainStyles: {
        dark: {
          bg: 'gray.700',
          color: 'whiteAlpha.900'
        },
        light: {
          bg: 'white',
          color: 'gray.900'
        }
      },
      form: {
        name: '',
        email: '',
        message: ''
      }
    }
  },
  computed: {
    colorMode () {
      return this.$chakraColorMode()
    },
    theme () {
      return this.$chakraTheme()
    },
    toggleColorMode () {
      return this.$toggleColorMode
    }
  },
  methods: {
    async sendContactToLambdaFunction () {
      try {
        const response = await this.$axios.$post('/.netlify/functions/contact-mail', {
          name: this.form.name,
          email: this.form.email,
          message: this.form.message
        })

        this.$toast({
          title: 'Mail sent',
          description: response,
          status: 'success',
          duration: 10000,
          isClosable: true
        })

        this.form.name = ''
        this.form.email = ''
        this.form.message = ''
      } catch (error) {
        this.$toast({
          title: 'An error occured',
          description: error,
          status: 'error',
          duration: 10000,
          isClosable: true
        })
      }
    }
  }
}
</script>

When triggered, the async sendContactToLambdaFunction() makes an API request to our Netlify function (we’ll get to that in the next section).

If we get to the browser, we should see something like this:

Nuxt.js Serverless Contact Form

At this stage, we have our UI and logic ready but we don’t have any API endpoint. In the last section, we’ll be making calls to /.netlify/functions/contact-mail, which doesn’t exist yet.

Before we do that, let’s take a moment to understand what Netlify Functions are.

What are Netlify Functions?

The most popular serverless architecture — or function-as-a-service (FaaS) — provider is AWS Lambda. But AWS isn’t suitable for small-scale apps. Netlify lets you deploy serverless Lambda functions without an AWS account, and management is handled directly within Netlify.

Netlify also provides a way to test your serverless functions locally with Netlify Dev. Let’s make sure we have it installed.

// NPM
npm install netlify-cli -g

// Yarn
yarn add global netlify-cli

Now let’s create an netlify.toml file in the project’s root directory. This configuration file tells Netlify how to build and deploy the project.

We’ll also require it for our local development environment.

// netlify.toml

[dev]
   command = "yarn dev"
[build]
  command = "yarn generate"
  publish = "dist"
  functions = 'functions'  ## directs netlify to where your functions directory is located

[[headers]]
  ## Define which paths this specific [[headers]] block will cover.
  for = "/*"
    [headers.values]
    Access-Control-Allow-Origin = "*"

Create the Netlify function by running the command below.

netlify functions:create contact-mail

Then, select the [hello-world] basic function that shows async/await usage and response formatting option. This command will create a functions directory in the project’s root directory and a contact-mail.js file.

To test this function locally, run:

netlify dev

This will start up the development server.

Then:

netlify functions:invoke contact-mail --no-identity

You should get something like this:

{"message":"Hello World"}

nuxt vue serverless developer programming

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.

Developer Career Path: To Become a Team Lead or Stay a Developer?

For a developer, becoming a team leader can be a trap or open up opportunities for creating software. Two years ago, when I was a developer, ... by Oleg Sklyarov, Fullstack Developer at Skyeng company

Vue.js Web App Development | Skenix Infotech

Our expert Vue.js developers follows Agile methodology that delivers high-quality & affordable Vue.js services. Hire Vue.js Developer from Skenix Infotech.

Serverless-side rendering with Vue.js, Nuxt.js and AWS Lambda

We want the best of both worlds. The SEO boost server-side rendering provides, and the speed of a Single Page Application. All this while hosted basically for free in a serverless environment on AWS Lambda. Here’s a quick overview of what we’ll be building for you to get up to speed. Feel free to jump to the step that interests you the most.

Why Every Vue developer should Checkout Vue 3 Now - CodeSource.io

Vue 3 offers a lot of amazing new features. This article will introduce you to the new advancement in Vue 3, new features introduced to the framework, and what has changed.