Mailing a Postcard with JavaScript Part 1
Tags: tutorial, javascript, node, beginners
Published: 2021-11-18 16:57:50


##Creating a Postcard with Lob and Node.js
Lob’s Print & Mail and Address Verification APIs enable developers to interact with Lob’s services programmatically. You can mail a postcard or letter to your customers at critical points in their journey as easily as you might send an email. These physical reminders help you keep in touch with clients, and encourage clients to keep purchasing your products and services.	

In this three-part tutorial, we’ll create a postcard template, verify our recipient’s address, send a postcard, and track it along its journey. We’ll create a Javascript application to do all this, so our users can access everything they need in one place. 

Complete code for tutorial [available on GitHub](https://github.com/lob/lob-node-examples/tree/main/sending-postcard-with-js-part1).

To follow along, you’ll need your own Lob account. You can [sign up](https://dashboard.lob.com/#/register?utm_source=devto&utm_medium=blog&utm_campaign=devrel_tutorial_postcard) here and find your API keys in your settings. Take a note of the secret and the publishable API keys. We’ll use the publishable key any time we interact with Lob from the frontend and the secret key anywhere we access the Lob API from the backend.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xa2seq57cd450b4tt9iu.png)

Lob’s APIs are well documented, and we can [choose from SDKs](https://www.github.com/lob/) in various languages. We’ll focus on Node.js in this series, but the overall approach will work in whichever language you choose.

## Our template creation app				
Our app comprises two parts: a Vue frontend and a Node backend. In this part of our tutorial, we’ll enable our users to create postcard templates that they can later use to send physical postcards to their customers.

Our users will create the template with HTML and CSS then store it on the Lob server. This template has the layout and text ready to send to all our user’s customers. Once we submit these templates to Lob, we can use them as many times as we’d like. We could send hundreds — or even thousands — of postcards from a single template.
		
Let’s start creating our application by giving our users the ability to build and submit their own templates. In this tutorial, we’ll use one of [Lob’s example postcard templates](https://www.lob.com/template-gallery#postcards) and allow our users to change the background picture and text.

Creating the application’s Vue front end
First, let’s instantiate a new Vue application using Vite:
{% gist https://gist.github.com/SidneyAllen/578c7f365e1da53e5983543da0cf1cd6.js %}
Let’s name our project and select Vue. We won’t use TypeScript.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/84eigxqwy9q5v5rhb4si.png)

We follow the instructions Vite displays on our screen to install the dependencies and get the starter site up and running.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s9tkgyhjq3mi21beywim.png)			

Point your browser to localhost:3000 to see the boilerplate app.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k8lc6xws70hhjjd60h19.png)
	
Before we start making our application, create a file called .env to save our environment variables. The Vite framework exposes environment variables that have a “VITE_” prefix. For more information on this, read the Vite documentation. As a developer, you never want to make a commit to Github that contains sensitive login information. 

### Save your .env file in the root folder.
{% gist https://gist.github.com/SidneyAllen/22e173867b2f54d0801985e3f4cb5e3d.js %}

Now, let’s create a new component for our front template, Front.vue, and add the template and styling based on one of Lob’s examples. Specifically, we look at the front of the Product Promotion postcard. We will replace the default HelloWorld component with the new Front component in the App.vue file. 
 
### src/App.vue
{% gist https://gist.github.com/SidneyAllen/eac7d8d572a43b64f326204636318df3.js %}
 
### src/components/Front.vue
{% gist https://gist.github.com/SidneyAllen/7435f223abb51ead9f512bd02a70a261.js %}

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nn4qws5epugp1hmlg7y1.png)

We want to allow our users to change each of these elements. We’ll use the Vue composition API to help us do that.

We add a &lt;script setup&gt; tag to our component and set up some reactive variables. We then set the default values to those the template already uses, so nothing changes on the frontend when we update the template.

{% gist https://gist.github.com/SidneyAllen/0d677ef7934497d12f9a45d9252c547c.js %}

Now that we have reactive values, we need to give our users some way to interact with those values. We use the v-model to create a two-way binding between the input and the reactive value for the header and logo text. As we type into these fields, we’ll be able to see the form updating.
 
{% gist https://gist.github.com/SidneyAllen/f8005ae4dffbcbe641d8e6285f21150d.js %}

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/275lloa0ovzxvammcp60.png)

We then upload the image to a third-party service, like Cloudinary. Cloudinary has a helpful library that provides the upload modal, handles the cloud storage, and provides a URL we can pass into our template.

We first need to add the script import for Cloudinary to our main index.html file right above the “main.js” script tag that holds our Vue app:
{% gist https://gist.github.com/SidneyAllen/6e8a2a0da5b62e7dac4d175b1dd46d25.js %}
 
When we instantiate the Cloudinary script, it adds a cloudinary library with an openUploadWidget to our window object. 

Let’s create a handler function to open the widget and update our state when the widget completes. To follow along, sign up for [Cloudinary](https://cloudinary.com/users/register/free) to get your cloud name and [upload preset](https://cloudinary.com/documentation/upload_presets). Put these values in the .env file we created earlier. 
 
{% gist https://gist.github.com/SidneyAllen/840cbbb2796ee0cd8c3ffe1957753923.js %}
 
Next, we add a button to our template that will trigger this widget when the user clicks.
 
{% gist https://gist.github.com/SidneyAllen/01c2b613326e21739ee1f4fa49eedf0d.js %}
 
The next tasks we need to tackle is to bring some routing to our Vue app. After saving the postcard template, we want the app to redirect to another page that will list all of the templates that we have saved.   

Add the vue-router package to our project by running the following command: “npm install --save vue-router@4”. Create a new file under src/router/index.js and add the following:

{% gist https://gist.github.com/SidneyAllen/5f1b92301d755ba1df30791d1e49add9.js %}

Since we are missing the ListTemplates component, let’s create a stub of this for this time being.

{% gist https://gist.github.com/SidneyAllen/22391e7300695745137a51bfa2627bee.js %}

The last step we need to do is put a reference to the router in the main.js file and update the App.vue component to use the router.

### src/main.js
{% gist https://gist.github.com/SidneyAllen/1e2f227d3f49748359f4cd307007e627.js %}

### src/App.vue
{% gist https://gist.github.com/SidneyAllen/f87d107a5ec6dff2088ce279b6a3fafd.js %}

Now, we add our template name. Then, we send the template information to our backend.
 
{% gist https://gist.github.com/SidneyAllen/ec7916f2120f5f7be2d9eb13e3c55f0a.js %}

Let’s next hop over to the backend and get our route ready to receive this information.		

## Creating the application’s Node backend
To create our back end, we will create a new folder called “backend.” After changing into this directory, we will create a package.json file with the following contents:

{% gist https://gist.github.com/SidneyAllen/0297b9d8733ca02c5fd11c8f5c83f3f2.js %}

This package.json file lists our dependencies --  express web framework to structure our app; dotenv to keep our environment variables secret; cors to handle data sent to our front end; and nodemon to restart our server every time we save. We added "type": "module" to our package.json to use esm import and export. Run the command “npm install” to install all of our dependencies.

Let’s next create an index.js file and add a basic web server setup. We also make and import router.js to organize our routes.

### index.js
{% gist https://gist.github.com/SidneyAllen/a73fffda8f685d8e1697dc6d4948abff.js %}
 
### router.js 
{% gist https://gist.github.com/SidneyAllen/f78545d1c628df2429ed531501d43397.js %}
 
After we set this up, we will need to create a .env file that will hold our Lob API test key. 

{% gist https://gist.github.com/SidneyAllen/61d2a3fcd6649c5e29be730c0b1cf685.js %}

We’ll be sending the variables as query parameters from Vue to our backend. We have the replicated template on the back end and populate it with the user’s front-end data.
 
{% gist https://gist.github.com/SidneyAllen/be90c3aa638f7ee949cbb0616ac7733c.js %}
 
We’re effectively adding dynamic values to a large template literal. We’ll use node-fetch, a Node implementation of the browser fetch API, to send our data to Lob. We need to encode the data and identify ourselves with the API correctly. Let’s modify the createTemplateHandler function to add the call to Lob API. 
 
{% gist https://gist.github.com/SidneyAllen/59264e687e17303e74c3edaf0b1709c1.js %}

To keep the third-party packages to a minimum, we use Node’s UrlSearchParams rather than a package such as form-data. UrlSearchParams also sets the headers we need automatically.			
We append our description and HTML parameters to the data we send to Lob, then prepare our headers. We use a basic username and password to authenticate ourselves with the Lob API. The username should be our API key, which we get from the environment variable LOB_SECRET_API_KEY, and the password should be blank. This configuration is the same as setting an Authorization header, as the code above shows.

Once our authentication is successful, we send a message back to our Vue application to let it know we’re done.
 
{% gist https://gist.github.com/SidneyAllen/1dd86244d86efaaa246f031f1dfb3414.js %}
 
Now that we’ve created the template, we make a route to list our templates and consume the route on the frontend. In Node, we use a straightforward GET request using node-fetch:
 
{% gist https://gist.github.com/SidneyAllen/1e874ab83618cd0e57da1ecd5365353f.js %}

Now that we have the functionality to grab our saved templates from the Lob API, let’s add that endpoint to the Express app. 

{% gist https://gist.github.com/SidneyAllen/f5d6e61a38d309728dfa83389b7dade8.js %}

We authenticate ourselves in the same way, then pass that data on to our clients. We want to get that data in Vue and display it to our users. We fetch and process the data using the onMounted function. We then update our reactive value, which triggers our template to rerender. So let’s update the ListTemplates component that we stubbed out earlier.
 
{% gist https://gist.github.com/SidneyAllen/d69196bf14220b852980acb7932b5202.js %}
		
Using the v-for directive, we iterate over the templates and destructure the more relevant values.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zlyae2anynt04wa17xyh.png)

## Next steps
In this part of the tutorial, we’ve built our application to enable users to create and view templates in Lob. We have the [project code saved here](https://github.com/lob/lob-node-examples/tree/main/sending-postcard-with-js-part1) for you to review as you carry on to the next part of this tutorial. Next time, we’ll use these templates to send our real-life postcards, changing bits to atoms.
		
A well-designed postcard can enhance the relationship between your customers and your brand. [Try Lob’s Print & Mail API](https://www.lob.com/print-mail) yourself now, or continue to the second part of this tutorial to learn how to verify an address before sending a postcard.