DEV Community

Cover image for Building a Secure and Compliant Message Center with React & DataMotion
Janelle Phalon
Janelle Phalon

Posted on • Updated on

Building a Secure and Compliant Message Center with React & DataMotion

Welcome to the first tutorial in our series on building a secure and compliant email client with DataMotion's secure message center v3 APIs. Today, we'll focus on setting up the server and making two essential API calls: obtaining an access token and securely fetching message summaries. By the end, you'll have laid a solid foundation, preparing you for more advanced topics in our subsequent tutorials.

Ready to get started? First, let's check the prerequisites.

Prerequisites

  • Familiarity with Node.js and React.
  • Node.js, git, and npm installed.
  • A text editor or IDE.
  • Access to DataMotion's v3 APIs.

πŸ”— Note: Before diving in, if you haven't tested the secure message center v3 APIs yet, check out our previous tutorial on testing DataMotion APIs with Insomnia. It provides a detailed guide on ensuring the APIs are functional.

Now that we've validated the APIs, let's put them into action!

Starter Files

Begin by cloning the starter files here.

git clone <url> 
cd DataMotion-SMC-starter-code
npm install
Enter fullscreen mode Exit fullscreen mode

These files provide foundational React components: Navbar, Sidebar, and Inbox. The starter files also come with basic styling, ensuring the focus remains on integrating with DataMotion's secure message center APIs.

1. Setting Up the Backend with DataMotion APIs

Starting with the backend, let's first navigate to your server directory.

mkdir server
cd server
Enter fullscreen mode Exit fullscreen mode

a. Initiate the server

Initiate the project with default configurations:

npm init -y
Enter fullscreen mode Exit fullscreen mode

This creates a package.json file that keeps track of all the dependencies and scripts for your project.

b. Installing Essential Libraries

For our server setup, we'll need:

  • express: A framework to build our server.
  • axios: To make HTTP requests.
  • cors: To enable Cross-Origin Resource Sharing.
  • dotenv: To manage environment variables from a .env file.

Install these libraries with:

npm install express axios cors dotenv
Enter fullscreen mode Exit fullscreen mode

c. Setting up the Basic Server

Create a server.js file (or whatever you've named your main server file).

touch server.js
Enter fullscreen mode Exit fullscreen mode

Let's set up a basic Express server:

const express = require('express');
const axios = require('axios');
const cors = require('cors');

require('dotenv').config();

const app = express();
const PORT = 5000;

app.use(cors());  
app.use(express.json());

app.get('/', (req, res) => {
    res.send('Server is running!');
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Now, start the server using:

node server.js
Enter fullscreen mode Exit fullscreen mode

You should see a message indicating that the server is running on http://localhost:5000. Visiting this URL in your browser should display "Server is running!"

d. DataMotion API Integration in Server

With our server up and running, let's integrate DataMotion's APIs. For more details and in-depth information on the available API endpoints and their requirements, refer to DataMotion's developer center.

Before proceeding, create and populate your .env file with your DataMotion credentials.

  • Fetching an Access Token:

Add the following endpoint to your server:

app.get('/token', async (req, res) => {
    try {
        const response = await axios.post('https://api.datamotion.com/SMC/Messaging/v3/token', {
            grant_type: "client_credentials",
            client_id: process.env.CLIENT_ID, // assuming you have named it CLIENT_ID in .env
            client_secret: process.env.CLIENT_SECRET // assuming you have named it CLIENT_SECRET in .env
        });
        res.json(response.data);
    } catch (error) {
        res.status(500).json({ message: "Error fetching token", error: error.response.data });
    }
});
Enter fullscreen mode Exit fullscreen mode
  • Fetching Emails:

Now, introduce the endpoint to fetch messages:

app.get('/messages', async (req, res) => {
    try {
        // First, get the token
        const tokenResponse = await axios.post('https://api.datamotion.com/SMC/Messaging/v3/token', {
            grant_type: "client_credentials",
            client_id: process.env.CLIENT_ID, // assuming you have named it CLIENT_ID in .env
            client_secret: process.env.CLIENT_SECRET // assuming you have named it CLIENT_SECRET in .env
        });

        // Use the token to get the message summaries
        const messagesResponse = await axios.get('https://api.datamotion.com/SMC/Messaging/v3/content/messages/?folderId=1&pageSize=10&pageNumber=1&sortDirection=DESC&metadata=true', {
            headers: {
                Authorization: `Bearer ${tokenResponse.data.access_token}`
            }
        });

        res.json(messagesResponse.data);
    } catch (error) {
        res.status(500).json({ message: "Error fetching messages", error: error.response.data });
    }
});
Enter fullscreen mode Exit fullscreen mode

e. Verifying Backend Setup

Having integrated DataMotion's secure message center APIs into our server, it's vital to check if everything works as expected before proceeding to the frontend.

Restart your server and visit http://localhost:5000/messages in your browser. If the setup is correct, you'll see a list of your messages rendered in a JSON format, confirming that our backend is fetching data using the APIs and is ready to serve the frontend.

2. React Frontend: Fetching and Displaying Emails

To initiate the frontend, open a fresh terminal window and directly start the React project. Upon launching, the file should display with mock email data:

npm start 
Enter fullscreen mode Exit fullscreen mode

To integrate the server APIs with our frontend, we'll primarily utilize two hooks from React: useState and useEffect. Before going into the code, let's understand them:

  • useState: A hook that gives a component its own data storage. It returns the data's current value and a function to update it. When the data changes, the component re-renders.

  • useEffect: A hook that runs code after the component renders. We use it here to fetch emails once the component appears on screen.

a. API Call with useEffect

Inside Inbox.js, initiate the fetch with the useEffect hook:

import React, { useState, useEffect } from 'react';
import { ListGroup } from 'react-bootstrap';

const Inbox = () => {
    const [emails, setEmails] = useState([]);

    useEffect(() => {
        // Call our server to get emails
        fetch('http://localhost:5000/messages')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                // Sort emails by createTime from newest to oldest
                const sortedEmails = data.items.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
                setEmails(sortedEmails);
            })
            .catch(error => {
                console.error('Error fetching messages:', error);
            });
    }, []);

   // Helper function to format the date or show the time if the email was received today
    const formatDate = (dateString) => {
      const date = new Date(dateString);
      const today = new Date();
      if (date.toDateString() === today.toDateString()) {
          return date.toLocaleTimeString();
      }
      return date.toLocaleDateString();
  };

    return (
        // Rendering logic here...
    );
};

export default Inbox;
Enter fullscreen mode Exit fullscreen mode

b. Displaying Emails:

DataMotion's developer center outlines the response structure. Using this, we'll extract and showcase key details like the sender's email, subject, and creation time.

// ... rest of the Inbox component ...

  return (
    <div className="col-md-9 pt-3">
        <ListGroup className='inbox-style'>
          {emails.map(email => (
              <ListGroup.Item key={email.messageId} className='email-item'>
                  <div>
                      {/* Email Address of Sender */}
                      <p className="sender-email">{email.senderAddress}</p>
                      {/* Email Subject */}
                      <p className="email-subject">{email.subject}</p>
                  </div>
                  {/* Email Received Date/Time */}
                  <div className="date-received">{formatDate(email.createTime)}</div>
              </ListGroup.Item>
          ))}
      </ListGroup>
   </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

After implementing these steps, simply refresh the page, and you should see a list of your emails securely displayed!

Conclusion

By integrating DataMotion's APIs with React, we've set the foundation for a secure and compliant email client application. Understanding each phase empowers you, the developer, to further adapt and enhance this setup. Stay tuned for our next tutorial where we'll dive deeper into DataMotion's secure message center APIs, exploring functionalities like creating drafts and sending messages.

For a more detailed overview of secure messaging, check out DataMotion's secure message center. With this series, we're just starting our journey into the vast capabilities offered by DataMotion. Happy coding!

Top comments (0)