Search code examples
multi-tenantfaunadb

Programmatically creating Faunadb child database


Hi I am new in Faunadb and trying a multi-tenancy app. There is option of creating child databases from fauna shell. But my thinking is when a user is signed up, a child database with that username will create automatically.

I searched in there documentation but got no idea. Is it possible from frontend JS libraries such as React, Vue or from API in Nodejs?

Thanks is advance.


Solution

  • Yes, you can programatically create a child database using CreateDatabase. Two things are important to note here:

    • The key you use for creating the child db must have the admin role, so you'd want to do it from a secure backend node server.
    • Which database you connect to in fauna is defined by which key you use to connect, so you must generate and use another key for the new child database.

    This is how the code might look:

    // Connect to the parent database
    const parentFauna = new faunadb.Client({
      secret: FAUNA_ADMIN_KEY
    })
    
    // Create child database and retrieve a new key for it
    const { secret } = await parentFauna.query(
      Do(
        CreateDatabase({
          name: "example"
        }),
        CreateKey({
          database: Database("example"),
          role: "server"
        })
      )
    )
    
    // You can now connect to the child database
    const childFauna = new faunadb.Client({
      secret: secret
    })