{"id":20994029,"url":"https://github.com/michelderu/astra-express-react","last_synced_at":"2026-04-10T11:31:34.895Z","repository":{"id":80119633,"uuid":"384464609","full_name":"michelderu/astra-express-react","owner":"michelderu","description":"Dummies guide to set up a React front-end and Express middle-layer communicating with a DataStax Astra backend","archived":false,"fork":false,"pushed_at":"2021-07-19T07:35:50.000Z","size":282,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-07-18T21:18:45.333Z","etag":null,"topics":["astra","datastax","expressjs","nodejs","react"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/michelderu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-07-09T14:37:51.000Z","updated_at":"2021-07-19T07:35:53.000Z","dependencies_parsed_at":"2023-07-09T13:33:05.965Z","dependency_job_id":null,"html_url":"https://github.com/michelderu/astra-express-react","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/michelderu/astra-express-react","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michelderu%2Fastra-express-react","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michelderu%2Fastra-express-react/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michelderu%2Fastra-express-react/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michelderu%2Fastra-express-react/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/michelderu","download_url":"https://codeload.github.com/michelderu/astra-express-react/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michelderu%2Fastra-express-react/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31641114,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-10T07:40:12.752Z","status":"ssl_error","status_checked_at":"2026-04-10T07:40:11.664Z","response_time":98,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["astra","datastax","expressjs","nodejs","react"],"created_at":"2024-11-19T07:16:31.694Z","updated_at":"2026-04-10T11:31:34.878Z","avatar_url":"https://github.com/michelderu.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Getting started with DataStax Astra, Express and React (for dummies)\nAs I didn't create a full stack application before (mostly focussed on back-end) I decided to figure it out and share my experience in this guide. Hence its *for dummies* name 😅.\n\nThis repository shows an end-to-end way to build a React front-end with an Express middle layer communicating to DataStax Astra.\n\n![architecture diagram](images/astra-express-react.png)\n\nFor learning purposes you can start from scratch and just follow the steps. In that case don't clone this repo 😀.\n\nThanks to the nice guide by [João Henrique](https://www.freecodecamp.org/news/create-a-react-frontend-a-node-express-backend-and-connect-them-together-c5798926047c/)!\n\n## 1️⃣ Set up the middle layer\n### Generate the basic Express setup\n```sh\nnpx express-generator api\n```\n### Change the port number for the middle layer\nInside the `api` directory, go to `bin/www` and change the port number on line 15 from `3000` to `9000`.\n### Create a middle layer service\nOn `api/routes`, create a `testAPI.js` file and paste this code:\n```js\nvar express = require(\"express\");\nvar router = express.Router();\n\nrouter.get(\"/\", function(req, res, next) {\n    res.send(\"API is working properly\");\n});\n\nmodule.exports = router;\n```\n### Tell Express to use the new service\nOn the `api/app.js` file, insert a new route on line 24:\n```js\napp.use(\"/testAPI\", testAPIRouter);\n```\nOk, you are “telling” express to use this route but, you still have to require it. Let’s do that on line 9:\n```js\nvar testAPIRouter = require(\"./routes/testAPI\");\n```\n### Allow cross-origin requests in the middle layer\n```sh\ncd api\nnpm install --save cors\n```\nOn your code editor go to the API directory and open the `api/app.js` file.\nOn line 6 require CORS:\n```js\nvar cors = require(\"cors\");\n```\nNow on line 18 “tell” express to use CORS:\n```js\napp.use(cors());\n```\n### 🚀 Test your new service\nBuild and start your middle layer:\n```sh\ncd api\nnpm install\nnpm start\n```\nNow browse to http://localhost:9000/testAPI and you will see the message: \"API is working properly.\"\n\nCongratulations! You just created an Express middle-layer that exposes a REST endpoint!\n\n## 2️⃣ Set up the front-end\n### Generate the basic Express setup\n```sh\nnpx create-react-app front-end\n```\n### Call the middle layer API from the front-end\nUpdate file `frontend/src/App.js` to the following:\n```js\nimport React, { Component } from 'react';\nimport logo from './logo.svg';\nimport './App.css';\n\nclass App extends Component{\n  constructor(props) {\n    super(props);\n    this.state = { apiResponse: \"\" };\n  }\n\n  callApi() {\n    fetch(\"http://localhost:9000/testAPI\")\n      .then(res =\u003e res.text())\n      .then(res =\u003e this.setState({ apiResponse: res }))\n      .catch(err =\u003e err);\n  }\n\n  componentDidMount() {\n    this.callApi();\n  }\n\n    render() {\n        return (\n        \u003cdiv className=\"App\"\u003e\n            \u003cheader className=\"App-header\"\u003e\n            \u003cimg src={logo} className=\"App-logo\" alt=\"logo\" /\u003e\n            \u003cp className=\"App-intro\"\u003e{this.state.apiResponse}\u003c/p\u003e\n            \u003c/header\u003e\n        \u003c/div\u003e\n        );\n    }\n}\n\nexport default App;\n```\n### 🚀 Test the front-end, talking to the middle layer\nOpen another terminal and run:\n```sh\ncd front-end\nnpm start\n```\nNow browse to http://localhost:3000 and you will see the message: \"API is working properly.\"\n\nCongratulations! You just created a React front-end that calls a service in the Express middle-layer!\n\n## 3️⃣ Let the middle layer communicate with the DataStax Astra backend\n### Add dependencies\nIn the `api` directory run:\n```sh\nnpm install @astrajs/collections @astrajs/rest@0.0.12 dotenv --save\n```\n### Set up Astra configuration\nFirst create a `.env` file in the `api/` directory and fill in the correct settings for your database. You can find these on the Connect tab underneath the REST option in the Astra Management interface (https://astra.datastax.com).\n```sh\nASTRA_DB_ID=\nASTRA_DB_REGION=\nASTRA_DB_KEYSPACE=\nASTRA_DB_APPLICATION_TOKEN=\n```\n### Call Astra REST endpoints\nThen update the `testAPI.js` file to set up the connection with Astra and retrieve all tables in your keyspace:\n```js\nvar express = require(\"express\");\nvar router = express.Router();\n\n// Retrieve settings from .env file\nrequire('dotenv').config();\n\nvar astraRest = require(\"@astrajs/rest\");\nvar astraClient;\nvar restBasePath = \"/api/rest/v1/keyspaces/\" + process.env.ASTRA_DB_KEYSPACE;\nvar restSchemaPath = \"/api/rest/v1/keyspaces/\" + process.env.ASTRA_DB_KEYSPACE + \"/tables/\";\n\n// Create an astra client if not available\nasync function getAstraClient() {\n    if (!astraClient) {\n        astraClient = await astraRest.createClient({\n            astraDatabaseId: process.env.ASTRA_DB_ID,\n            astraDatabaseRegion: process.env.ASTRA_DB_REGION,\n            authToken: process.env.ASTRA_DB_APPLICATION_TOKEN,\n        });\n    }\n    return astraClient;\n}\n\n// Get all tables\nasync function getTables() {\n    astraClient = await getAstraClient();\n    var response = await astraClient.get(restSchemaPath);\n    return response;\n}\n\n// Listen\nrouter.get(\"/\", function(req, res, next) {\n    getTables().then(function(data){\n        res.send(data.data);\n      }).catch(function(err){\n        res.send(\"Exception: \" + err);\n      })\n});\n\nmodule.exports = router;\n```\n### 🚀 Watch the magic happen in the middle layer\nCtrl-c the middle layer and restart:\n```sh\nnpm start\n```\nNow browse to http://localhost:9000/testAPI and you will see all tables in your keyspace.\n\n### 🚀 Watch the magic happen in the browser\nReload your page and watch what happens on http://localhost:3000\n\n## 4️⃣ Let's create a Todo front-end\n### First create a todo schema in Astra\nBrowse to https://astra.datastax.com, log in to your CQL Console and switch to your keyspace by `use \u003ckeyspacename\u003e;`.\n\nNow let's create a simple table to store our todos:\n```sql\nCREATE TABLE todo (\n  name text,\n  date date,\n  priority text,\n  PRIMARY KEY ((name), date, priority)\n)\nWITH CLUSTERING ORDER BY (date DESC, priority ASC);\n```\nAnd let's store some data:\n```sql\nINSERT INTO todo (name, date, priority) VALUES ('Create back-end', '2020-07-12', 'high');\nINSERT INTO todo (name, date, priority) VALUES ('Create front-end', '2020-07-13', 'high');\nINSERT INTO todo (name, date, priority) VALUES ('Eat ice cream', '2020-07-14', 'low');\n```\nGreat! We have a schema and some data to play with.\n### Now expose this data through a middle-layer endpoint\nIn `api/routes` we'll create a new route called getTodos.js. As a simple starter `cp testAPI.js getTodos.js`.\n\nNow update getTables() to the following:\n```js\n// Get all Todos\nasync function getTodos() {\n    astraClient = await getAstraClient();\n    var response = await astraClient.get(restBasePath + \"/tables/todo/rows\");\n    return response;\n}\n```\nMake sure to call the new function in the `get` function, like:\n```js\n// Listen\nrouter.get(\"/\", function(req, res, next) {\n    getTodos().then(function(data){\n        res.send(data.data.rows);\n      }).catch(function(err){\n        res.send(\"Exception: \" + err);\n      })\n});\n```\nNow update `api/app.js` so that it knows there is a new route:\n1. On line 11 add `var getTodosRouter = require(\"./routes/getTodos\");`\n2. On line 29 add `app.use(\"/getTodos\", getTodosRouter);`\n\n### 🚀 Watch the magic happen in the middle layer\nCtrl-c the middle layer and restart:\n```sh\nnpm start\n```\nNow browse to http://localhost:9000/getTodos and you will see all your todos!\n\n## 5️⃣ It's time to show our todo table in the front-end\nIn `frontend/src` we'll create a new renderer called Todos.js. As a simple starter `cp App.js Todos.js`. Our new renderer will be responsible for outputting a nicely formatted list of todos.\n\nUpdate the file to match the following:\n```js\nimport React, { Component } from 'react';\nimport './App.css';\n\nclass Todos extends Component{\n  constructor(props) {\n    super(props);\n    this.state = { apiResponse: [{\"name\": \"\", \"date\": \"\", \"priority\": \"\"}] };\n  }\n\n  callApi() {\n    fetch(\"http://localhost:9000/getTodos\")\n      .then(res =\u003e res.text())\n      .then(res =\u003e this.setState({ apiResponse: JSON.parse(res) }))\n      .catch(err =\u003e err);\n  }\n\n  componentDidMount() {\n    this.callApi();\n  }\n\n  render() {\n    return (\n      \u003cdiv class=\"container-fluid\"\u003e\n        \u003cdiv class=\"row\"\u003e\n          \u003cdiv class=\"col-md-12\"\u003e\n            \u003ctable class=\"table\"\u003e\n              \u003cthead\u003e\n                \u003ctr\u003e\n                  \u003cth\u003eName\u003c/th\u003e\n                  \u003cth\u003eDate\u003c/th\u003e\n                  \u003cth\u003ePriority\u003c/th\u003e\n                \u003c/tr\u003e\n              \u003c/thead\u003e\n              \u003ctbody\u003e\n                {this.state.apiResponse.map(item =\u003e (\n                  \u003ctr class={item.priority === \"high\" ? \"table-danger\" : \"table-active\"}\u003e\n                    \u003ctd\u003e{item.name}\u003c/td\u003e\n                    \u003ctd\u003e{item.date}\u003c/td\u003e\n                    \u003ctd\u003e{item.priority}\u003c/td\u003e\n                  \u003c/tr\u003e\n                ))}\n              \u003c/tbody\u003e\n            \u003c/table\u003e\n          \u003c/div\u003e\n        \u003c/div\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n\nexport default Todos;\n```\nNow we have to invoke it from the front-end. In `src/index.js` change the following:\n1. On line 4 change App into Todo as: `import Todos from './Todos';`\n2. On line 9 call the Todos rendering as: `    \u003cTodos /\u003e`\n\nAnd we also want some eye candy which means we'll include [Bootstrap](https://getbootstrap.com/). To enable the stylesheet, open `public/index.html` and add `\u003clink rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"\u003e` right before the closing `\u003c/head\u003e` tag.\n\n### 🚀 Watch the magic happen in the browser\nReload your page and watch what happens on http://localhost:3000\n\nCongratulations! You now know how to build an end-to-end app using APIs communicating with Astra!","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichelderu%2Fastra-express-react","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmichelderu%2Fastra-express-react","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichelderu%2Fastra-express-react/lists"}