Deploy a react app with serverless function in minutes (online demo):
-
Create a basic react app
$ npx create-react-app netlify-react-demo --use-npm
-
Go into project
$ cd netlify-react-demo
-
Install netlify
$ npm i -g netlify-cli $ npm i -D netlify-cli
-
Install axios & random-words
$ npm i axios random-words
-
Launch your IDE
$ code .
-
Create a serverless function ./functions/hello.js
const randomWords = require('random-words') const handler = async (event, context) => { const { length } = event.queryStringParameters console.log('length param:', length) console.log('aws request ID:', context.awsRequestId) return { statusCode: 200, body: JSON.stringify({ message: randomWords({ exactly: Number(length), join: ' ' }), }), } } module.exports = { handler }
-
Add NPM script to ./package.json
{ "scripts": { "dev": "netlify dev" } }
-
Create Netlify manifest ./netlify.toml
[build] command = 'npm run build' functions = 'functions' publish = 'build' [dev] autoLaunch = false
-
Run dev server
$ npm run dev
-
Run dev server
$ npm run dev
-
Test the servless function web service
$ http http://localhost:8888/.netlify/functions/hello length==5
-
Update App react component ./src/App.js to consume the web service
import logo from './logo.svg' import './App.css' import { useState } from 'react' import axios from 'axios' function App() { const [message, setMessage] = useState() const [input, setInput] = useState() const fetchData = async () => { const length = input ? Number(input) : 1 const params = new URLSearchParams([['length', length]]) const results = await axios.get('/.netlify/functions/hello', { params }) setMessage(results.data.message) } return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Word generator</h2> <p> <input value={input} onChange={(e) => setInput(e.target.value)} /> </p> <p> <button onClick={fetchData}>Click to generate words</button> </p> <p>{message}</p> </header> </div> ) } export default App
-
Deploy the web app with netlify
-
Log in to netlify
$ netlify login
-
Create a new site
$ netlify sites:create --name demo-hello-words
-
Link project to site
$ netlify link
-
Build web app
$ npm run build
-
Deploy
$ netlify deploy
-
Test draft URL
$ xdg-open https://6139d9ceef9e2bd79d6303a2--demo-hello-words.netlify.app
-
Deploy to main URL
$ netlify deploy --prod
-
Browse main URL
$ xdg-open https://demo-hello-words.netlify.app
-