JavaScript Tutorials - Kinsta® https://kinsta.com/topic/javascript-tutorials/ Kinsta: Simply better hosting. Wed, 18 Feb 2026 05:53:24 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.5 https://kinsta.com/wp-content/uploads/2024/09/cropped-Kinsta-black-favicon-1-32x32.png JavaScript Tutorials - Kinsta® https://kinsta.com/topic/javascript-tutorials/ 32 32 How to set up TypeScript with Express https://kinsta.com/blog/express-typescript/ Fri, 09 Feb 2024 14:10:30 +0000 https://kinsta.com/?p=174466&preview=true&preview_id=174466 TypeScript is a strongly typed programming language that extends JavaScript capabilities. It offers a range of features to help you develop scalable applications with Node.js and ...

The post How to set up TypeScript with Express appeared first on Kinsta®.

]]>
TypeScript is a strongly typed programming language that extends JavaScript capabilities. It offers a range of features to help you develop scalable applications with Node.js and Express.

One of the critical advantages of TypeScript over JavaScript is that it provides type classes, making it easier to write more predictable and maintainable code. Additionally, TypeScript offers type safety, ensuring your code is free from runtime errors and making detecting flaws early in development easier. The language also comes with refactoring tools and autocompletion, which improves developers’ experience.

Moreover, Node.js and Express provide excellent performance for applications of any scale. Using classes in TypeScript also helps with organization and structure, further aiding in scalability. With these tools, you can build robust and scalable applications to handle growing demand.

This article demonstrates setting up an Express application using TypeScript with a single endpoint. Then, it explains how to deploy your application to Kinsta’s application hosting.

How to create an Express server

To follow this tutorial, ensure you have Node.js and npm installed on your computer. To set up an Express server:

  1. Create a directory using the code below:
    mkdir sample_app && cd sample_app
  2. Initialize a Node.js application in the directory by running this command:
    npm init -y

    The -y flag in the command accepts the default prompts when creating a package.json file populated with the following code:

    { 
      "name": "sample_app",
      "version": "1.0.0",
      "description": "", 
      "main": "index.js", 
      "scripts": { 
        "test": "echo \"Error: no test specified\" && exit 1" 
      }, 
      "keywords": [], 
      "author": "", 
      "license": "ISC" 
    }
  3. Next, install express for adding essential functionality and dotenv for environment variable management in the directory you just created by running this command:
    npm i express dotenv
  4. Create a .env file in the root of the sample_app directory and populate it with the variable below.
    PORT=3000
  5. Create an express application that responds with a Hello World text when users visit http://localhost:3000.
    const express = require("express");
    const dotenv = require("dotenv");
    
    // configures dotenv to work in your application
    dotenv.config();
    const app = express();
    
    const PORT = process.env.PORT;
    
    app.get("/", (request, response) => { 
      response.status(200).send("Hello World");
    }); 
    
    app.listen(PORT, () => { 
      console.log("Server running at PORT: ", PORT); 
    }).on("error", (error) => {
      // gracefully handle error
      throw new Error(error.message);
    })

    dotenv.config() populates your Node application’s process environment (process.env) with variables defined in a .env file.

  6. Start your Node.js application by running this command:
    node index.js

    Check if the application works by visiting http://localhost:3000 on your browser. You should get a response similar to this.

    Hello World server with Express
    Hello World on http:localhost:3000.

Enable TypeScript in an Express application

Follow the steps below to use TypeScript in an Express application:

  1. Install TypeScript by running this command:
    npm i -D typescript

    The -D option enables npm to install packages as dev dependencies. You can use the packages you install with this option in the development phase.

  2. One of the strengths of the TypeScript community is the DefinitelyTyped GitHub repository. It stores documentation of type definitions for various npm packages. Users can quickly integrate npm packages into their projects without worrying about type-related difficulties by only installing the type definition for those packages with npm.DefinitelyTyped is an indispensable tool for TypeScript developers. It enables them to write cleaner and more efficient code and reduce the likelihood of errors. You install the type definitions of both express and dotenv by running this command:
    npm install -D @types/express @types/dotenv
  3. To initialize TypeScript, run this command.
    npx tsc --init

    The generated tsconfig.json file indicates your TypeScript application’s root directory. It provides configuration options to define how TypeScript compilers should work. It includes a series of config options disabled or enabled, with comments explaining each option.

  4. Add an outDir property to the config object to define the output directory.
    {
      "compilerOptions": {
        // …
        "outDir": "./dist"
        // …
      }
    }

How to create a TypeScript server

To create a TypeScript server, change the .js extension to .ts and update the code with these type definitions:

import express, { Request, Response } from "express";
import dotenv from "dotenv";

// configures dotenv to work in your application
dotenv.config();
const app = express();

const PORT = process.env.PORT;

app.get("/", (request: Request, response: Response) => { 
  response.status(200).send("Hello World");
}); 

app.listen(PORT, () => { 
  console.log("Server running at PORT: ", PORT); 
}).on("error", (error) => {
  // gracefully handle error
  throw new Error(error.message);
});

To use the compiler package and compile the TypeScript file into JavaScript, run the command below in the root directory of your application.

npx tsc

Then start your application by running the command.

node dist/index.js

Visiting http://localhost:3000 on your browser should provide a “Hello World” response.

How to deploy your TypeScript server to Kinsta

Now, you’re ready to deploy your application to the web. You can deploy your application to many platforms, including Kinsta’s application hosting.

Before you push your application to a Git repository, using TypeScript and committing the compiled JavaScript file to Git isn’t advisable. Include a start script in the package.json file.

{
  // …
  "script": {
    "start": "npx tsc && node dist/index.js",
  }
  // …	
}

Also, create a .gitignore file in your application’s root directory and include node_modules and .env to prevent pushing these files to your Git provider.

Once your repository is set, follow these steps to deploy your application to Kinsta:

  1. Log in or create an account to view your MyKinsta dashboard.
  2. Authorize Kinsta with your Git provider.
  3. Click Applications on the left sidebar, then click Add application.
  4. Select the repository and the branch you wish to deploy from.
  5. Assign a unique name to your app and choose a Data center location.
  6. Use all default configurations. MyKinsta uses npm start as the entry point to deploy your application. If you want to use another command, you can adjust the runtime process in MyKinsta.
  7. Click Create application.

After deployment, MyKinsta provides a URL to access your application deployment publicly. You can visit the page to confirm it displays “Hello World.”

Summary

This guide demonstrated how to develop and set up an Express Application using TypeScript and deploy the application with Kinsta. TypeScript has extra capabilities that JavaScript does not — including type classes, type safety, refactoring tools, and auto-completion — to help you build scalable applications and catch errors during development.

Kinsta helps you deploy your application fast with enhanced security and stability. With 27 data centers offering high-performance servers, which runs on a powerful cloud infrastructure.

Have you used TypeScript in the past? What are your thoughts on using it with an Express server?

The post How to set up TypeScript with Express appeared first on Kinsta®.

]]>
How to set up TypeScript with Express Featured image for How to set up TypeScript with Express
Create and Deploy a Node.js App in 5 mins With Express https://kinsta.com/blog/create-express-app/ Fri, 15 Dec 2023 14:18:05 +0000 https://kinsta.com/?p=170315&preview=true&preview_id=170315 Express, the world’s most used Node.js framework, empowers developers to create backend web servers with JavaScript. This framework provides most of what backend developers need out ...

The post Create and Deploy a Node.js App in 5 mins With Express appeared first on Kinsta®.

]]>
Express, the world’s most used Node.js framework, empowers developers to create backend web servers with JavaScript. This framework provides most of what backend developers need out of the box, simplifying routing and responding to web requests.

We already have a guide on everything you should know about Express.js, so this hands-on article will show you how to use it. This tutorial explains how to create and deploy an example Node.js app using Express.js.

How To Make Apps Quickly With Express.js

This walkthrough demonstrates how to create a web application that takes requests to an endpoint, uses a parameter from the request to make a database call, and returns information from the database as JSON.

Prerequisites

To follow this tutorial, ensure you have the following installed on your computer:

  • Node.js and Node Package Manager (npm) — Essential runtime environment and package manager for JavaScript.
  • Git — Distributed version control system facilitating collaborative software development.

Express Application Generator

You can add Express to existing Node apps using the process outlined in our Express.js guide, but if you’re starting from scratch, there’s an even faster option: the Express generator.

The official Express generator from Express.js is a Node package that allows you to generate a new application skeleton. This can be done by first creating a folder for your application and then running the npx command (available in Node.js 8.2.0):

mkdir express-application
npx express-generator

Upon successful generation, the terminal displays a list of folders/files created and commands for installing dependencies and running the application. Install the dependencies by running the command below:

npm install

Next, launch your web server:

DEBUG=myapp:* npm start

The skeleton application has a prebuilt index route that renders a basic home page. You can view this in your browser by visiting localhost:3000.

Exploring the Skeleton Express Application

When you open your Express application in your preferred code editor, you will find a basic structure that forms the backbone of your web application.

/
|-- /node_modules
|-- /public
|-- /routes
    |-- index.js
    |-- users.js
|-- /views
    |-- error.jade
    |-- index.jade
    |-- layout.jade
|-- app.js
|-- package.json
  • node_modules: This directory stores all the installed dependencies and libraries for the project.
  • public: Contains static assets like CSS, JavaScript, images, etc. These files are served directly to the client’s browser.
  • routes: Holds files responsible for defining various routes and handling requests coming from different URLs.
  • views: Contains templates or views that the server renders to create the user interface. Here, error.jade, index.jade, and layout.jade are templates written in the Jade templating language. They help structure and render dynamic content to users.
  • app.js: This file typically serves as the entry point for the Express application. It’s where the server is configured, middleware is set up, routes are defined, and requests and responses are handled.
  • package.json: This file contains metadata about the application. It helps manage dependencies and project configuration.

Understanding Route Handling

In your Express application, the routes directory is where routes are defined as separate files. The primary route, often called the index route, resides in the routes/index.js file.

This index route deals with a GET request, responding with a web page generated in HTML by the framework. Below is the code snippet illustrating how a GET request is handled to render a basic welcome page:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
 res.render('index', { title: 'Express' });
});

module.exports = router;

If you modify the res.render() function to res.send(), the response type changes from HTML to JSON:

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send({ key: 'value' });
});

module.exports = router;

Expanding the capabilities, another route is added to the same file, introducing a new endpoint that accepts a parameter. This code snippet demonstrates how your application can handle traffic on a different endpoint, extract a parameter, and respond with its value in JSON:

/* GET a new resource */
router.get('/newEndpoint', function(req, res, next) {
  res.send({ yourParam: req.query.someParam });
});

Sending a GET request to localhost:3000/newEndpoint?someParam=whatever will yield JSON output containing the string “whatever”.

A GET request is made to the locally running application in Postman
A GET request is made to the locally running application in Postman.

Express and Kinsta Application Hosting

Making web requests from your computer to your computer is neat, but web development isn’t complete until you’re off localhost. Fortunately, Kinsta makes deploying applications to the web easy, even if you need a database.

Now, let’s delve into expanding your application’s capabilities by integrating database functionality and deploying both the application and the database to the web, enabling access from any computer.

Before deploying your Express application to Kinsta’s Application Hosting, it’s crucial to push your application’s code and files to your chosen Git provider (Bitbucket, GitHub, or GitLab). Ensure you create a .gitignore file in your application’s root directory and include node_modules to prevent pushing these files to your Git provider.

Once your repository is set, follow these steps to deploy your Express application to Kinsta:

  1. Log in or create an account to view your MyKinsta dashboard.
  2. Authorize Kinsta with your Git provider.
  3. Click Applications on the left sidebar, then click Add application.
  4. Select the repository and the branch you wish to deploy from.
  5. Assign a unique name to your app and choose a Data center location.
  6. Configure your build environment next. Select the Standard build machine config with the recommended Nixpacks option for this demo.
  7. Use all default configurations and then click Create application.

Kinsta works with the Express application generator right out of the box! Once you complete these steps, your application will automatically begin the build and deployment process.

The deployment screen will provide a URL where Kinsta deploys your application. You can append /newEndpoint?someParam=whatever to test out the endpoint built in the previous section of this article.

How To Add a Database to Express Application

For most production-level applications, having a database is essential. Luckily, Kinsta simplifies this process by providing fully managed database services that are incredibly easy to set up.

Here’s how you can create a database on Kinsta:

  1. Navigate to the Databases section on the sidebar of MyKinsta’s dashboard.
  2. Click Create a database. Configure your database details by entering a name and selecting the database type.
  3. Select the PostgreSQL option. A Database username and password is automatically generated:

    The MyKinsta database configuration step of adding a new database
    The MyKinsta database configuration step of adding a new database.
  4. Select the same Data center location where you hosted your Express application and configure your desired size.
  5. Confirm payment information and click Create database.

Once the database is successfully created:

  1. Access the database details by clicking on it. In the Overview page, navigate to the Internal connections section.
  2. Select the appropriate application.
  3. Check the option to Add environment variables to the application.
  4. Click on Add connection to connect the newly created database and your application.

Next, copy the connection string of the newly created database to connect to it with a database tool. Any SQL connection tool will suffice, but this demonstration uses Beekeeper. Open the app and click Import from URL, paste the connection string, and click Import. This will let you execute SQL on the Kinsta-hosted database you just created.

Next, create an elementary table with a single entry by executing some SQL statements against the hosted database with your database tool:

CREATE TABLE "States"
( id integer CONSTRAINT states_pk PRIMARY KEY,
  state_name varchar(100),
  capital varchar(100),
  state_bird varchar(100),
  "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

INSERT INTO "States"
VALUES(1, 'ohio', 'columbus', 'cardinal');

Add the following database packages to your project:

npm install sequelize pg

The sequelize dependency is an ORM for Node.js, and pg serves as the PostgreSQL client, enabling interaction between Node.js applications and PostgreSQL databases.

Next, write the application code that accepts a GET request with an id parameter and returns the information in the database associated with that id. To do so, alter your index.js file accordingly:

var express = require('express');
var router = express.Router();
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize(process.env.CONNECTION_URI, {
  dialect: 'postgres',
  protocol: 'postgres',
});

const State = sequelize.define('State', {
  // Model attributes are defined here
  state_name: {
  type: DataTypes.STRING,
  allowNull: true,
  unique: false
  },
  capital: {
  type: DataTypes.STRING,
  allowNull: true,
  unique: false
  },
  state_bird: {
  type: DataTypes.STRING,
  allowNull: true,
  unique: false
  },
}, {
  // Other model options go here
});

async function connectToDB() {
  try {
  sequelize.authenticate().then(async () => {
  // await State.sync({ alter: true });
  })
  console.log('Connection has been established successfully.');
  } catch (error) {
  console.error('Unable to connect to the database:', error);
  }
}
connectToDB();

/* GET a new resource */
router.get('/state', async function(req, res, next) {
  const state = await State.findByPk(req.query.id);
  if (state) {
   res.send(state)
  } else {
   res.status(404).send("state not found");
  }
});


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

/* GET a new resource */
router.get('/newEndpoint', function(req, res, next) {
  res.send({ yourParam: req.query.someParam });
});

module.exports = router;

Commit the code changes and push them to your Git repository. Then, proceed to redeploy manually on Kinsta or await automatic deployment.

Now, when you query the /states endpoint with id=1, you’ll receive a state from the database.

A GET request to the fully functioning application hosted in MyKinsta
A GET request to the fully functioning application hosted in MyKinsta.

That’s all there is to it! You can check out the complete project code on GitHub.

Summary

This article demonstrated how the Express framework makes creating and deploying a Node.js application quick and easy. You can create a new application with the Express generator in just a few simple steps. With Kinsta Application Hosting, deploying the app is streamlined and requires minimal setup.

The power and ease of using the Express framework for Node.js application development are significant. With Kinsta, you can carry the momentum that Express and Node.js give you into the deployment phase of your project without wasting time with configuration.

What are your thoughts on the Express application generator? Have you utilized it to develop any applications previously? Feel free to share your experiences in the comments below!

The post Create and Deploy a Node.js App in 5 mins With Express appeared first on Kinsta®.

]]>
Create and Deploy a Node.js App in 5 mins With Express Featured image for Create and Deploy a Node.js App in 5 mins With Express
Create a Kinsta-Hosted To-Do List Using the Jira API and React https://kinsta.com/blog/jira-api/ Mon, 04 Dec 2023 15:21:50 +0000 https://kinsta.com/?p=169889&preview=true&preview_id=169889 Jira is a popular project management tool that helps you keep track of tasks within a project. However, when working on a large project, your Jira ...

The post Create a Kinsta-Hosted To-Do List Using the Jira API and React appeared first on Kinsta®.

]]>
Jira is a popular project management tool that helps you keep track of tasks within a project. However, when working on a large project, your Jira dashboard can become cluttered as the number of tasks and team members increases.

To address this concern, you can use the Jira REST API to generate a simplified To-Do List application that displays your assigned tasks and their deadlines. The API lets you programmatically interact with Jira to create, retrieve, update, and delete issues and access user data and project details.

This tutorial walks you through developing a to-do list application with Node.js as the server to fetch issues from your Jira account and a React application to display them. You also learn how to host both the frontend and server to Kinsta.

Prerequisites

To follow along, you need:

How To Build the Backend With Node.js and Express

Express is a popular Node.js framework that provides a streamlined environment for building server-side applications. Express simplifies the handling of routes and facilitates interactions with external resources, such as APIs, databases, and frontend applications.

Follow the steps below to set up the server:

  1. Create a new directory and navigate to it. Then, initialize Node.js by running the command below:
    npm init -y

    This command creates a package.json file with the default settings at the root of your app’s folder.

  2. Next, install all the necessary dependencies for your project by running the following command:
    npm install express dotenv axios

    The command above installs the following:

    • express — A minimal Node.js framework for building APIs.
    • dotenv — A module that loads .env variables to process.env to let you securely access them.
    • axios — A promise-based HTTP client for Node.js. You use it to make API calls to Jira.
  3. Once the installation is successful, create a .env file in the root of your project and add the PORT number:
    PORT=3000

    This is the port number the server listens to. You can change it to a port of your choice.

  4. Create an index.js file in your project’s root folder and add the following code to import Express, create an instance of an Express application, and start your server:
    const express = require('express');
    require('dotenv').config()
    const app = express();
    const PORT = process.env.PORT;
    
    // Define routes here
    
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}`);
    });
  5. Finally, in your package.json file, add a script to start your server:
    "scripts": {
       "start": "node index"
      },

    Now, you can run the start script in your terminal:

    npm run start

    This command starts your server. You should see the following text logged in the terminal:

    Server is running on port 3000

    With the server up and running, you can now configure your Jira app.

How To Configure a Jira App

To use the Jira REST API, you need to authenticate a user account with your Jira site. The to-do app API you build uses basic authentication with an Atlassian account email address and API token.

Here’s how to set it up:

  1. Create a Jira account or log in if you have one.
  2. Navigate to the security section of your Atlassian profile and click Create API token.
  3. In the dialog that appears, enter a Label for your token (e.g., “jira-todo-list”) and click Create.
  4. Copy the token to your clipboard.
  5. Finally, store the API Token in your .env file:
    JIRA_API_TOKEN="your-api-token"

    Now, you can access the Jira API using basic authentication.

Set Up Routes To Fetch Issues From Jira

Now that you have configured a Jira application. Let’s set up routes to fetch issues from Jira in your Node.js server.

To initiate a request to the Jira API, you must use the Jira API token you saved in the .env file. Retrieve the API token using process.env and assign it to a variable named JIRA_API_TOKEN in your index.js file:

const JIRA_API_TOKEN = process.env.JIRA_API_TOKEN

Now, you need to define the endpoint URL for your API request. This URL contains your Jira domain and a Jira Query Language (JQL) statement. The Jira domain refers to the URL for your Jira organization and looks like org.atlassian.net, where org is your organization’s name. JQL, on the other hand, is a query language for interacting with issues in Jira.

Start by adding the Jira domain to the .env file:

JIRA_DOMAIN="your-jira-domain"

You also need to store your Jira email to the .env file as it would be used for authorization when making a request to Jira:

JIRA_EMAIL="your-jira-email"

Next, add both environment variables and construct the endpoint URL using the domain and the following JQL statement. This query filters issues with “In progress” or “To do” statuses for the logged-in user and then orders them by status:

const jiraDomain = process.env.JIRA_DOMAIN;
const email= process.env.JIRA_EMAIL;

const jql = "status%20in%20(%22In%20progress%22%2C%20%22To%20do%22)%20OR%20assignee%20%3D%20currentUser()%20order%20by%20status";
 
const apiUrl = `https://${jiraDomain}/rest/api/3/search?jql=${jql}`;

Before creating a route, also import Axios into your index.js file:

const axios = require("axios")

You can now create a route make a GET request to the Jira API and return the issues. In index.js add the following code:

app.get('/issues/all', async (req, res) => {
  })

Now, use the axios.get method to make a GET request to the Jira REST API. You create the Authorization header by base64-encoding your Jira email and API token:

const response = await axios.get(apiUrl, {
        headers: {
        Authorization: `Basic ${Buffer.from(
          `${email}:${JIRA_API_TOKEN}`
        ).toString("base64")}`,
        Accept: "application/json",
      },
    });

Await the response from the Jira API and save it in a variable. The response contains a property called issues, which holds an array of issue objects:

const data = await response.json();
const { issues } = data;

Next, iterate over the issues array, extract only the relevant information about the to-do items, and return it in JSON response:

let cleanedIssues = [];
issues.forEach((issue) => {
      const issueData = {
        id: issue.id,
        projectName: issue.fields.project.name,
        status: issue.fields.status.name,
        deadline: issue.fields.duedate,
      };
      cleanedIssues.push(issueData);
});
res.status(200).json({ issues: cleanedIssues });

If you make a request to http://localhost:3000/issues/all, you should receive a JSON object containing the issues:

curl localhost:3000/issues/all

You can even take this further by using a provider like SendGrid and a cron job to send daily emails containing your assigned tasks.

Host Your Node.js Application on Kinsta

Before hosting your application on Kinsta, enable Cross-Origin Resource Sharing (CORS) to prevent an access-control-allow-origin error since you host the backend and the frontend on different domains. To do this:

  1. Install the cors npm package by running this command in your terminal:
    npm install cors
  2. Then, import the package in index.js.
    const cors = require('cors')
  3. Next, configure CORS as middleware to enable it for every incoming request. Add the following code at the top of your index.js file:
    app.use(cors());

    You can now send HTTP requests to your server from a different domain without encountering CORS errors.

Next, push your code to a preferred Git provider (Bitbucket, GitHub, or GitLab) and follow the steps below to host it:

  1. Log in or create an account to view your MyKinsta dashboard.
  2. Authorize Kinsta with your Git provider.
  3. Click Applications on the left sidebar, then click Add application.
  4. Select the repository and the branch you wish to deploy from.
  5. Assign a unique name to your app and choose a data center location.
  6. Add the environment variables. There’s no need to add the PORT as an environment variable, as Kinsta handles it automatically. Check the boxes next to Available during runtime and Available during build process:

    A form for adding key-value pairs of environment variables
    Kinsta app environment variables.
  7. Review other information (you can leave the default values) and click Create application.

Your server is now successfully deployed to Kinsta. On the left-hand menu, click Domains and copy the primary domain. This is your server’s URL endpoint.

Create a React Application to Display the Issues

Next, you use React to build your app’s frontend and CSS to style it. Follow the steps below to create a React project with Vite:

  1. Scaffold a new React project named jira-todo:
    npx create-vite jira-todo --template react
  2. Navigate to the project directory and install the necessary dependencies:
    npm install
  3. Start the development server:
    npm run dev

Fetch Issues From the Server

  1. Clear the contents in App.jsx and add the following code:
function App() {

  return (
    <div className="App">
      <h1>What's on my list today?</h1>
      {/* Display issues */}

   </div>
 );
}

export default App;
  1. Before you start fetching the issues, store the server URL from Kinsta in a .env file at the root of your app’s folder:
VITE_SERVER_BASE_URL="your-hosted-url"
  1. Get the URL in App.jsx by adding the following line at the top of the file:
const SERVER_BASE_URL=import.meta.env.VITE_SERVER_BASE_URL
  1. In your component, create an async function named fetchData and make a GET request to the /issues/all endpoint on the Express server. Once you receive a response, parse it as JSON and store the data in a state value named data:
import { useCallback, useEffect, useState } from "react";

function App() {
  const SERVER_BASE_URL=import.meta.env.VITE_SERVER_BASE_URL

  const [data, setData] = useState([]);
  const fetchData = useCallback(async () => {
    try {
      const response = await fetch(`${SERVER_BASE_URL}/issues/all`);
      if (!response.ok) {
        throw new Error('Network response was not ok');
     }
      const data = await response.json();
      	setData(data.issues);
    } catch (error) {
      console.error('Error fetching data:', error);
  }
     },[SERVER_BASE_URL]);

  useEffect(() => {
    // Fetch data when the component mounts
    fetchData();
     },[fetchData]);

  return (
    <div className="App">
        <h1>What's on my list today?</h1>
      
    </div>
  );
}

export default App;

Note that you use the useEffect hook to execute the fetchData function when the component mounts.

Render the Issues From Jira in the Browser

  1. Now, you can modify the return statement of your component to iterate over the issues and list them in the browser:
return (
  <div>
    <h1>What's on my list today?</h1>
    <section>
      	{data && data.map(issue => {
      	return <div className="issues" key={issue.id}>
        <div>
         <div>{issue.summary}</div>
          <small>{issue.deadline}</small>
        </div>
        <div>
          <div> className="status">{issue.status}</div>
        </div>
      </div>
    })}
    </section>
  </div>
);
  1. To style this application, add the following CSS code to App.css:
h1 {
    text-align: center;
  font-size: 1.6rem;
  margin-top: 1rem;
}
section {
  display: flex;
  flex-direction: column;
 justify-content: center;
  align-items: center;
  margin-top: 2rem;
 }

 .issues {
  display: flex;
  min-width: 350px;
  justify-content: space-between;
  padding: 1rem;
  background-color: #eee;
  margin-bottom: 1rem;
}

 small {
  color: gray;
}

.status-btn {
  padding: 4px;
  border: 1px solid #000;
  border-radius: 5px;
}
  1. Then, import App.css in index.js to apply the styles:
import './App.css'

Now, when you start your application, you should see a list of tasks assigned to you with their status and deadline in your browser:

A screenshot of the React application page
List of Jira issues assigned to a user.

Deploy Your React Application on Kinsta

To keep things simple, use Kinsta’s Static Site Hosting to deploy the application. Kinsta’s Static Site Hosting helps build your sites into a static site and deploys the static files ensuring swift content delivery and minimal downtime.

Create a repository on GitHub to push your source code. Once your repo is ready, follow these steps to deploy your static site to Kinsta:

  1. Log in or create an account to view your MyKinsta dashboard.
  2. Authorize Kinsta with your Git provider.
  3. Click Static Sites on the left sidebar, then click Add site.
  4. Select the repository and the branch you wish to deploy from.
  5. Assign a unique name to your site.
  6. MyKinsta detects the build settings for this React project automatically. You see the following settings prefilled:
    • Build command: npm run build
    • Node version: 18.16.0
    • Publish directory: dist
  1. Add the URL of your server as an environment variable using VITE_SERVER_BASE_URL.
  2. Finally, click Create site.

And that’s it! You now have a deployed site within a few seconds. A link is provided to access the deployed version of your site. If you navigate to your site’s domain, you see a list of Jira issues. You can later add your custom domain and SSL certificate if you wish.

As an alternative to Static Site Hosting, you can opt for deploying your static site with Kinsta’s Application Hosting, which provides greater hosting flexibility, a wider range of benefits, and access to more robust features. For example, scalability, customized deployment using a Dockerfile, and comprehensive analytics encompassing real-time and historical data.

Summary

In this guide, you learned how to create an Express app to retrieve assigned Jira issues using the Jira REST API. Additionally, you connected a React frontend application to your Express application to display these issues in the browser.

This app is a rudimentary demonstration of what you can achieve with Jira REST API. You can enhance your app with functionality that lets you mark completed tasks, perform advanced filtering, and much more.

Also, with Kinsta, you can host both your server and the site in one dashboard using our various services. Check out Kinsta’s robust, flexible web hosting for all your applications.

The post Create a Kinsta-Hosted To-Do List Using the Jira API and React appeared first on Kinsta®.

]]>
Create a Kinsta-Hosted To-Do List Using the Jira API and React Featured image for Create a Kinsta-Hosted To-Do List Using the Jira API and React