Send Emails with SendGrid & Next.js Serverless Functions - Contact Form Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey team we're gonna learn how to programmatically send emails with sendgrid and nexjs api routes i'm colby fayock and if this is your first time here make sure you hit subscribe for future updates sending emails to communicate with others throughout the web is a critical way of how our world works with sendgrid we can programmatically send those emails whether it's from our application or just from a general script for our use case though we want to use the sendgrid mail api and to do that we need to use an api key which we don't want to expose directly inside of a client-side application so we need some kind of server-side code in order to send those requests for our particular use case we're already going to be inside of a react application with nexus the cool thing is next.js supports api routes out of the box so we can safely make those requests with our api key and send any of our mail through that service so to see how this all works we're going to start off with create next app so in my terminal i'm going to run yarn create next app and then it's going to go ahead and get all the packages so that i can install and pre-load my application where i'm going to call it my email app where it's going to install all the dependencies and get us started and once it's done i can cd into that directory i can even run yarndev which will start up a development server which i can open up in my browser and we can see that once it loads i have my new nexjs app so starting off inside of my text editor vs code we can see that in the pages directory i have this index.js file which is going to serve as my home page for our demo i'm going to create a really basic contact form which just has a few fields like commonly named email and just a simple message so that we can test how our mail api endpoint actually works with sendgrid so inside of my page i'm going to scroll down i'm going to get rid of all this content inside of my grid and i'm going to start off with a simple form with the method of post and then inside of that i'm going to start off with some paragraph tags and a label which html4 for name as our first one with the label of name and then input type equals text and let's call that name equals name and then i'll be our first input i went ahead and added another two for the email with the type of email and a text area for message and then finally i'm gonna add a paragraph tag with a button and we're gonna say submit so if i look inside of my application i can see that it's not really the most usable form in the world so i'm going to add a few tweaks with it where inside of here i'm going to add a new style tag where i'm going to add jsx so we can write some jsx in here and then inside the string tag here let's say we want our label to display block and even add a little bit of margin bottom for 2em i'm also going to save my button let's add a background color of blue violet a color of white add some padding oops point eight am one am i think that'll be good order of none order radius of 0.2 am and let's see how it looks so far i think that's good enough for our purposes where we're going to be able to enter that name or email address as well as a message for fun we can also modify some of the other features on this page like i'm gonna go and i'm gonna say please be a human i'm gonna make this a contact form i'm gonna get rid of that footer at the bottom and i think that's good enough for now so ultimately what we want to happen is when somebody fills out this form and clicks submit we want to capture that request that form submission and we want to send an actual request to our api endpoint that we'll set up in a few minutes here just as a quick disclaimer here make sure that if you're serving an open web form with an open endpoint that you're using some kind of spam prevention and security measures to make sure that people aren't compromising those accounts and making sure that you're not gonna get overwhelmed with emails so to start off in our code we're gonna add a submit handler so we'll say on submit right on our form element we're gonna define a new function handle on submit where i'm gonna copy that function name go up to the top of my component i'm going to define that function i'm going to create an async function called handle on submit where the first thing we're going to do is we're going to pass in an argument which is going to be our event and we're going to say e prevent default which is going to say hey form we don't want you to actually submit to the browser the next thing we want to do is actually grab all that data from our form so we're going to first define a new form data object where inside of that we're going to create a new array so array from where we're going to take the current target from our event so e current target and this is going to be our form and what we want to access is our forms elements just as a quick aside to see how this works if we go to our web console we can search for that form inside of our dom where we have our form right here if we type in elements right after we can see that we get this collection of inputs which is what we're going to use to capture all of our form data the only issue with this collection is it's not by default an array so that's why we have to wrap it with array from which will turn it into something that'll be iterable for us to actually loop through and grab that data so i'm going to say on that array for each field i'm going to say first of all if we have a field without a name which by default our button will come through as a field without a name we're going to say if field name we're going to add an exclamation point so we can say if there is not a field with a name then we're just going to simply return but otherwise we're going to say form data and we're going to say our field name is equal to our field value so what we should end up with is an object where we have a bunch of properties that are associated with the name of each of our fields and their value and we can test out what this looks like by console logging out our form data now if we try to submit this form we can see that we have that object where we have our keys and we have our values so now that we have this form data we want to actually do something with it and that's where our api route is going to come in where we're going to take this form data and we're going to send it up to that api route where it's then going to process that data it's going to send it to sendgrid which is going to send an email for us if you're not familiar with the next.js api routes they actually come with one by default where we can see that it's located at pages api hello we already see that our homepage is being loaded at localhost but if we open this up in a new tab and go to api hello we can see that we get that object with john doe right inside of our browser as a get request now for our purposes we can go ahead and create a new file but let's just reuse what we have here i'm going to rename this hello to mail because ultimately this is going to be a mail endpoint and instead of name john doe i'm going to return status okay which is just a common practice for when returning a 200 status which is successful and now we can see if we go to our new api endpoint for mail we get our status of okay so at this point we have a working api endpoint but what we want to do next is actually accept some data as a payload from our application so we can use that to process that mail request now what happens is whenever we trigger this endpoint if we're sending data along with it this request object the req which stands for request is going to include a body property which is going to have that data as a string so what we're going to do is we're going to create a new constant called body which we're going to set equal to json parse that request dot body where what it's going to do is because it's coming in as a string and we know ahead of time that we're going to be sending json to that we're going to parse that json so that we can access it as a normal object as our body we can also test that out to make sure it's working by console logging out our body now back inside of our application we want to actually send this form data to that endpoint so we're going to use the fetch api which comes in pre-baked into next yes where we're going to run fetch and we're going to specify that endpoint so api slash mail and we're going to actually set an option for our second argument with a method of post and we're going to also send in a body where we're going to send jason stringify our form data and now if we go back to our application and we try submitting that again we can still see that we're getting that console log out inside of the terminal from when we're logging out the form data but if we go over to our terminal we can see that we're now getting a console log with that data from our node api which is our api endpoint so that means inside of this next.js endpoint we have access to all that same form data that we just passed in from our next.js application so now that we have our contact form working and we have our api endpoint able to accept that data the next thing we need to do is set up sendgrid so we can actually take that data and send it as an email if this is your first time using sendgrid you can head over to sendgrid.com where you can sign up for a free account and they have a nice free tier where you won't have to pay a thing for sending some emails now when we first get into the dashboard if this is our first time using it we'll have some options here where we can get started but if this isn't your first time or even if it is we can go into our settings where we're going to go down to sender authentication where we're going to authenticate a domain a custom domain with our dns provider so that we can send emails as that custom domain now for this next part you're going to need your own custom domain in order to authenticate it so you can send requests on behalf of that domain if you don't have your own custom domain i'm pretty sure you can still use sendgrid to actually send emails but i highly recommend that you use your own custom domain to send emails to make sure that people are getting a better experience when they're knowing that those emails are actually coming from you and your domain so once we're ready we can hit get started to authenticate our domain we can select our dns host which for our purposes i'm going to use google domains so i'm going to select google cloud and you can also select if you want to brand your links from this domain i'm going to leave it as the default for no but you can change that if you know what you're doing to whatever you'd like and here we're going to add the domain that we're going to be using for our email so in our example here jane doe at example.com so for my demo i'm going to use feyock.com and now when i click next i can see that i get this list of dns records or cnames that i'm going to need to add inside of my dns provider which in my case is google domains now for this walkthrough i'm going to use google domains which is the current service that i use for all of my domains but what we are going to be doing here should be very similar no matter what provider you use whether it's godaddy or namecheap or whatever so in particular with my domain i'm going to head over to the dns section where if i scroll all the way down to the bottom here we can see that we can define some custom resource records in particular we can see that we have these two inputs where we're going to want to select from the drop down the c name which is exactly what cengrid wants us to add so back over to sendgrid i'm going to copy and paste all these dns names as our name field and these canonical names as our value inside of google domains now the trick here is when we're actually copying this over to google domains we won't only want to enter the beginning of each of these fields we don't want to include the actual domain name on here so just as an example for this first one i can still just go ahead and copy the entire thing and paste it in here as a custom record but i'm going to remove this feyock.com i'm also going to grab the value of that and paste it in and we're going to remember to set that as a c name but then i can hit add we also want to make sure we take notice here that these records can take up to 40 hours 48 hours to actually propagate so make sure that you're not doing this with anything that's time sensitive or just keep in mind that that might take a little while to propagate if you're adding these records but now we can see that i went through and i added all these records and we can head back over to cengrid so now back in cengard we can see that i can go down here and i'm going to click i've added these records since i did and we can click verify now lucky for me since this was the first time i was adding those records they're brand new records so they're actually going to propagate more quickly or at least that's in my case with google domains so now that it worked we can go ahead and continue with our authentication so the next thing we're going to want to do is create an api key and we can do that by going over to the api keys section right here in the settings and if we select there we can see that currently if this is our new account we have no api keys but i'm going to create a new api key here i'm going to name it contact form which you can name it whatever you'll remember this key to actually be associated with but then we can also set the permissions now i'm going to leave mine at full access but you can just as easily go through the restricted access and customize with all the different permissions that you want for that particular key but just to keep going with this tutorial i'm going to keep it at full access i'm going to click create and view and we can see that i now have generated this new api key which is what i'm going to use for making those send grid requests now as it says here they're not going to be able to show this again so make sure you copy this key to a safe place so that you don't lose sight of it otherwise you'll have to delete this key and regenerate a new one but what we can do in the meantime is we're going to take this key and we're going to head back over to our application where we're going to use an environment variable so that we can substitute that value right inside of our code so inside of the root of our project i'm going to create a new file called.env.local i'm going to set a new variable of send grid api key and i'm going to set that equal to my key that i just got from the dashboard that way inside of our application and inside of our node function we're going to be able to access the send grid api key as an environment variable but once you have your api key saved we can click done and we can see that once it loads we can see that api key and we can even create a new one if we want next in order to actually send these emails we're going to use the mail service for the sendgrid web api and we can see if we scroll down here it gives us a few ways about how we can set this up but mostly what's important is we want to install this node package at sendgrid mail so in my terminal i'm going to go yarn add at sand grid slash mail and it's going to install our package and i'm going to go ahead and spin back up my development server now we want to actually import that package so we're going to say a new constant of mail we're going to set that equals to require that package name now before we can actually use this mail library we need to set our api key so we're going to say mail.set api key and we're going to set that equal to process.env.sendgrid.com underscore api key which is exactly what we set this variable for inside of our env.local file next we want to actually create a message that we're going to send with the mail api so i'm going to create a new constant called message and i'm going to set that equal to a template literal where we're going to be able to form our message so i'm going to say the name we'll set that equal to our body dot name i'm going to also add backslash r backslash n which is going to help us create a new line to format that for plain text emails so we'll also add our email and our message so email and message we probably don't need this rnn at the end of this one next we want to actually create the data payload that will send right directly into the mail api so we're going to say constant data is equal to spell that right constant theta is equal to two and i'm going to send this to hello colbyfayoc.com i'm going to set it from hello feyock.com which if you notice fayak.com is that domain that we're currently validating that we just set up inside ascend grid and because i have this domain authenticated i can really send this from wherever name i want whether this is hello or hi but i like to use hello so i'm going to leave it at that but also we can add a subject which i'm going to say new web form message then we wanna set the text property which is what we're going to set equal to message so if someone is receiving a plain text email they're going to receive that string which is why we set the slash r slash n but then finally we're gonna also set the html i'm gonna paste this one in here but we're gonna take the message and we're gonna replace those instances of slash r slash n and we're gonna replace all of them with a br or a break tag which is our way of setting a new line if we're actually sending html emails that would recognize that break tag and now finally once we have our data object we can simply run mail.send and we can pass in our data so now for the moment of truth we can actually test to see if this form is working and sending the emails on our behalf so if we head back over to our application we can click submit and we can see now right inside of my inbox we have our new web form message we have our name and our email and actually we have a little bit of a bug we have undefined so let's look quickly to see what that is if i look at my message i can see that i definitely type of that i'm sure some of you definitely caught that as i was working through it so let's change that to message i'm gonna go back into my application and let's click that to confirm it one more time we can even see the payload going out with our email message and name and yay now this time we can see that we have our name email and we have our message we can even see that this is coming from at feyock.com and for those of you who are interested we can even go to see the original message show original where we can see that this is coming right from sendgrid exactly how we set it up email is definitely a critical component of how our world works today and being able to have a contact form whether it's just for getting in touch with a personal blog or if you're trying to take business inquiries is an important way of being able to communicate with others the cool thing is between sendgrid's api or nexjs api routes we have a lot of flexible ways to be able to use these emails whether it is for contact messages like that or if we want to send notifications in case there's an error on our website what's your favorite use case of programmatically sending emails for something that's not necessarily a contact form let me know in the comments otherwise if you like this video make sure you hit thumbs up and subscribe for future updates thanks for watching you
Info
Channel: Colby Fayock
Views: 4,488
Rating: 5 out of 5
Keywords: send emails with javascript, send emails react, send emails, send emails using nodejs, send emails with nodejs, sendgrid, sendgrid tutorial, sendgrid nodejs, sendgrid api, sendgrid api key, sendgrid react, email api, email api javascript, sendgrid email api, next js send email, next js sendgrid, next js form, react forms, react form submit to api, next js api, nextjs api example, nextjs, contact form, contact form react, react contact form, react contact form send email
Id: QrVYLLpoyMw
Channel Id: undefined
Length: 18min 32sec (1112 seconds)
Published: Tue May 11 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.