Blog Building a Secure and Compliant Message Center with React and DataMotion

Building a Secure and Compliant Message Center with React and DataMotion

Welcome to a tutorial on building a secure and compliant email client using DataMotion’s Secure Message Center APIs. In this session, we will focus on setting up the server and executing two critical API calls: obtaining an access token and securely fetching message summaries. By the end of this tutorial, you will have established a […]

Welcome to a tutorial on building a secure and compliant email client using DataMotion’s Secure Message Center APIs. In this session, we will focus on setting up the server and executing two critical API calls: obtaining an access token and securely fetching message summaries. By the end of this tutorial, you will have established a solid foundation, preparing you for more advanced topics.

Ready to get started?

Prerequisites

To get the most out of this guide, have the following ready:

  • Familiarity with Node.js and React.
  • Node.js, git, and npm installed.
  • A text editor or IDE.
  • Access to DataMotion’s 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.

Setting up the Project

Begin by cloning the starter files here.

git clone <url> 
cd DataMotion-SMC-starter-code
npm install
Markdown


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

Setting Up the Backend with DataMotion APIs

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

mkdir server
cd server
Markdown

Initiate the server

Initiate the project with default configurations:

npm init -y
Markdown


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

 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
Markdown

Setting up the Basic Server

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

touch server.js
Markdown


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}`);
});
JavaScript


Now, start the server using:

node server.js
Markdown


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!”.

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.

Note: 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 });
    }
});
JavaScript

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 });
    }
});
JavaScript

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.

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 
Markdown


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.

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;
JavaScript

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>
  );
};
JavaScript


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. Want to enjoy the convenience of a secure message center with the power of secure and compliant AI? Sign up for our Free Trial of JenAI Assist for the best of all worlds!