Deploy a Serverless API React Application with TypeScript

Written on: March, 2024

2 min read

As for the rest. Netlify makes hosting fast and easy with serverless functions and continuous deployment. React enables you to quickly create reusable components. And TypeScript helps you write cleaner code that is easier to refactor. Lets go!

Steps

  1. Setup vite project with react and typescript
  2. First, you need to create a new vite project with react and typescript. Run the following command in your terminal.

    https://vitejs.dev/guide/
    1npm init vite@latest my-react-app -- --template react-ts
  3. Add typescript serverless functions to a Netlify project
  4. Next, you need to create a new Netlify project and add a typescript serverless function. Run the following command in your terminal. `npm i @netlify/functions` and then in your root folder netlify/functions add hello-world.ts file.

    https://github.com/Aldikrasniqi/serverless-typescript-react
    1import { Handler } from '@netlify/functions'
    2export const handler: Handler = async (event) => {
    3const { name, favoriteColor } = JSON.parse(event.body || '{}')
    4console.log('Hello ' + name + ', your favorite color is ' + favoriteColor)
    5return {
    6statusCode: 200,
    7headers: {
    8  /* Required for CORS support to work */
    9  'Access-Control-Allow-Origin': '*',
    10  /* Required for cookies, authorization headers with HTTPS */
    11  'Access-Control-Allow-Credentials': true,
    12},
    13body: JSON.stringify({
    14  name,
    15  favoriteColor,
    16  message: 'Hello ' + name + ', your favorite color is ' + favoriteColor,
    17}),
    18}
    19}
    20
    21            
  5. Create react costum hook for making API calls
  6. Create a new react costum hook for making API calls. This will help you to make API calls in a more efficient way. Run the following command in your terminal. `npm i axios` and then in your root folder src/hooks add useSubmit.ts file.

    https://reactjs.org/docs/hooks-custom.html
    1// useSubmit.ts
    2import { useState } from 'react'
    3import axios from 'axios'
    4
    5export function useSubmit() {
    6const [response, setResponse] = useState()
    7
    8async function handleSubmit(name: string, favoriteColor: string) {
    9// const localUrl = '/.netlify/functions/submit';
    10const deployUrl =
    11  'https://typescrpt-srvless.netlify.app/.netlify/functions/submit'
    12const headers = {
    13  'Access-Control-Allow-Origin': '*',
    14  'Access-Control-Allow-Headers': 'Content-Type',
    15  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
    16}
    17
    18try {
    19  const res = await axios.post(
    20    deployUrl,
    21    {
    22      name,
    23      favoriteColor,
    24    },
    25    {
    26      headers: headers,
    27    }
    28  )
    29
    30  setResponse(res.data)
    31  return res.data
    32} catch (error) {
    33  console.error(error)
    34  throw error
    35}
    36}
    37
    38return { handleSubmit, response }
    39}
    40
  7. Create a form for submitting data
  8. Create a new form for submitting data. This will help you to submit data to your serverless function. In your root folder src/components add Form.tsx file with the following code.

    https://reactjs.org/docs/forms.html
    1import React, { useState } from 'react'
    2import styles from './form.module.css'
    3import { useSubmit } from '../hooks/useSubmit'
    4export function Form() {
    5const [name, setName] = useState('')
    6const [favoriteColor, setFavoriteColor] = useState('')
    7
    8const { handleSubmit, response } = useSubmit()
    9
    10async function handleFormSubmit(
    11event: React.SyntheticEvent<HTMLFormElement>
    12) {
    13event.preventDefault()
    14
    15handleSubmit(name, favoriteColor)
    16  .then(() => {
    17    setName('')
    18    setFavoriteColor('')
    19  })
    20  .catch((error) => {
    21    console.error('Form submission error:', error)
    22  })
    23}
    24return (
    25<>
    26  <pre>{JSON.stringify(response, null, 2)}</pre>
    27  <form className={styles.form} onSubmit={handleFormSubmit}>
    28    <label htmlFor="name" className={styles.label}>
    29      Name:
    30    </label>
    31    <input
    32      name="name"
    33      type="text"
    34      id="name"
    35      value={name}
    36      className={styles.input}
    37      onChange={(e) => setName(e.target.value)}
    38    />
    39    <br />
    40    <br />
    41    <label htmlFor="favoriteColor" className={styles.label}>
    42      Favorite Color:
    43    </label>
    44    <input
    45      name="favoriteColor"
    46      type="text"
    47      id="favoriteColor"
    48      value={favoriteColor}
    49      className={styles.input}
    50      onChange={(e) => setFavoriteColor(e.target.value)}
    51    />
    52    <br />
    53    <br />
    54    <button type="submit" className={styles.submibutton}>
    55      Submit
    56    </button>
    57  </form>
    58</>
    59)
    60}
    61
  9. Deploy your project to Netlify
  10. Finally add your project to github and deploy it to Netlify. Netlify will automatically build and deploy your project with serverless functions configuration.

    https://www.netlify.com/blog/2016/09/29/a-step-by-step-guide-deploying-on-netlify/

Conclusion

Congratulations! You have successfully deployed a Serverless API React Application with TypeScript. You can now share your project with the world.
Back to Blogs
Aldi Krasniqi