Using SendGrid with Nuxt.js

Viewed 806

This post is not a question actually. More like help to the world for people who are struggling with Nuxt.js and SendGrid. I've been using stackoverflow for such a long time so maybe now it's my turn to start helping others.

I've been working on Nuxt.js WebApp development for the past 8 weeks. Nuxt.js is a massive learning curve and challenge for me but I really love working with this technology.

I spent the last 2 days developing sending the form with the use of SendGrid. There's not too much help online and I've been struggling a lot but I made it! So maybe some people will find my post useful.

Here's my form:

<form 
                        v-show="!isSubmitted"
                        class="contact-us__form" 
                        @submit.prevent="validate">

                        <b-form-group :class="{'form-group--error': $v.name.$error}">

                            <b-form-input
                                id="name"
                                v-model.trim="$v.name.$model"
                                type="text"
                                placeholder="Full Name">
                            ></b-form-input>

                            <div class="error" v-if="!$v.name.required">Field is required</div>
                            <div class="error" v-if="!$v.name.minLength">Name must have at least {{$v.name.$params.minLength.min}} letters.</div>

                        </b-form-group>
                        

                        <b-form-group :class="{'form-group--error': $v.phone.$error}">
                            <b-form-input
                                id="phone"
                                v-model.trim="$v.phone.$model"
                                type="number"
                                placeholder="Phone Number">
                            ></b-form-input>

                            <div class="error" v-if="!$v.phone.required">Field is required</div>

                        </b-form-group>
                        

                        <b-form-group :class="{'form-group--error': $v.email.$error}">
                            <b-form-input
                                id="email"
                                v-model.trim="$v.email.$model"
                                type="email"
                                placeholder="Email Address">
                            ></b-form-input>

                            <div class="error" v-if="!$v.email.required">Field is required</div>
                        </b-form-group>
                        

                        <div class="d-flex align-items-end">

                            <b-form-group :class="{'form-group--error': $v.message.$error}">
                                <b-form-textarea
                                    id="message"
                                    v-model.trim="$v.message.$model"
                                    type="text"
                                    placeholder="Message"
                                ></b-form-textarea>

                                <div class="error" v-if="!$v.message.required">Field is required</div>
                                <div class="error" v-if="!$v.message.minLength">Name must have at least {{$v.message.$params.minLength.min}} characters.</div>
                            </b-form-group>

                            <b-form-group>
                                <b-button 
                                    type="submit" 
                                    variant="secondary"
                                    v-html="'S'"
                                    :disabled="submitting" />
                            </b-form-group>
                        </div>
                    </form>

script:

    export default {
    mixins: [validationMixin],
    components: {
        subscribeBox
    },
    data() {
        return {
            map: bgMap,
            name: "",
            phone: "",
            email: "",
            message: "",
            submitting: false,
            isSubmitted: false,
            error: false,
        }
    },
    validations: {
        name: {
            required,
            minLength: minLength(4)
        },
        phone: {
            required,
        },
        email: {
            required,
            email
        },
        message: {
            required,
            minLength: minLength(5)
        }
    },
    methods: {
        validate() {
            if (this.$v.$invalid || this.$v.$error|| this.submitting) {
                this.$v.$touch();
                return
            }
            this.onSsubmit();
        },
        async onSsubmit() {
            this.submitting = true;
            this.error = false;

            try {
                await this.$axios.$post('/api/v1/send-email', {
                    name: this.name,
                    phone: this.phone,
                    email: this.email,
                    message: this.message,
                });
                this.submitting = false
                this.isSubmitted = true
                await new Promise(resolve => setTimeout(resolve, 2500))
            } catch(e) {
                this.submitting = false
                this.error = true
                console.error(e)
            }
        },

    },
}

nuxt.config.js

serverMiddleware: ['~/api/v1/send-email.js'],

api/v1/send-email.js (all the API Keys are placed in .env file)

const express = require("express");
const bodyParser = require('body-parser')
const sgMail = require('@sendgrid/mail');

const app = express();

sgMail.setApiKey(process.env.SENDGRID_API_KEY);

app.use(bodyParser.json())
app.post("/", (req, res) => {


    let msg = {
        to: req.body.email, // Change to your recipient
        from: '', // Change to your verified sender
        subject: 'Message from ' + req.body.name,
        text: 'telephone ' + req.body.phone + ', ' + 'message ' + req.body.message,
    }

    sgMail
        .send(msg)
        .then(() => {
            return res.status(200).json({ 'message': 'Email sent!' })
        })
        .catch((error) => {
            return res.status(400).json({ 'error': 'Opsss... Something went wrong ' + error })
        })

});

module.exports = {
    path: "/api/v1/send-email",
    handler: app
};

This app is still not finished but the code is working 100%! I'm new to Nuxt.js so some bits may not look awesome but I'm also happy and open to feedback and suggestions.

Thank you for reading my post and good luck with your project! :)

0 Answers
Related