node.jsreactjscassandradatastax-astrastargate-oss

Datastax Astra netlify and react-app, should I use nodejs client or REST API for serverless functions?


I built a simple react app with "create-react-app" and I want to use serverless functions with netlify. I use DataStax Astra Cassandra DB for that purpose, and created a netlify.toml config and .env variables (for the Database) inside my react project.

I set up a serverless functions folder for netlify:

const { createClient } = require('@astrajs/collections')

// create an Astra client
exports.handler = async function (event, context) {
    try {
        const astraClient = await createClient({
            astraDatabaseId: process.env.ASTRA_DB_ID,
            astraDatabaseRegion: process.env.ASTRA_DB_REGION,
            applicationToken: process.env.ASTRA_DB_APPLICATION_TOKEN,
        })
        // const basePath = `/api/rest/v2/KEYSPACES/${process.env.ASTRA_DB_KEYSPACE}/collections/messages`

        const messagesCollection = astraClient
            .namespace(process.env.ASTRA_DB_KEYSPACE)
            .collection('messages')
    const message = await messagesCollection.create('msg1', {
        text: 'hello my name is Marc!',
    })
    return {
        statusCode: 200,
        body: JSON.stringify(message),
    }
} catch (e) {
    console.error(e)
    return {
        statusCode: 500,
        body: JSON.stringify(e),
    }
}

it works when I run netlify dev , then my .env variables are injected into the .js file. However, I am wondering if I should use the nodejs datastax collections here, or the REST API functions from datastax (https://docs.datastax.com/en/astra/docs/astra-collection-client.html)? Because with react, it's essentially running in the browser or not? I am wondering why this still works with nodejs (because its not a nodejs environment with react, or is it?) I am getting access to my functions via localhost:8888/.netlify/functions/functionName is this served from a nodejs server or is it browser stuff?


Solution

  • it works when I run netlify dev , then my .env variables are injected into the .js file. However, I am wondering if I should use the nodejs datastax collections here, or the REST API functions from datastax (https://docs.datastax.com/en/astra/docs/astra-collection-client.html)? Because with react, it's essentially running in the browser or not?

    Correct - you would expose your Astra credentials to the world if you connect to your database directly from your React app.

    I am wondering why this still works with nodejs (because its not a nodejs environment with react, or is it?) I am getting access to my functions via localhost:8888/.netlify/functions/functionName is this served from a nodejs server or is it browser stuff?

    Netlify functions run serverside so it is safe to connect to Astra in your function code. Here's an example: https://github.com/DataStax-Examples/todo-astra-jamstack-netlify/blob/master/functions/createTodo.js