Using with FaunaDB
This integration only works if you have stored your users in FaunaDB. So, in case you are using Auth0, Okta, or store your users outside of FaunaDB, you will need to wait for our integration to support it.
SuperTokens provides an integration with FaunaDB that allows you to:
- Create a Fauna token for a user who just logged in
- Access the Fauna user token on your frontend client and backend APIs, so that you can query FaunaDB from anywhere
- Securely refresh the session and Fauna user token automatically
- Automatically revoke the Fauna user token when the session associated with that user is revoked.
Integration
Quick setup guide
1️⃣ Complete the- Make sure you have completed the frontend, backend and SuperTokens core setup.
override
config in Session.init()
2️⃣ Use the let supertokens = require("supertokens-node");
let Session = require("supertokens-node/recipe/session");
let { RecipeImplementation } = require("supertokens-node/recipe/session/faunadb");
supertokens.init({
supertokens: {...},
appInfo: {...},
recipeList: [
Session.init({
...
override: {
functions: (originalImplementation) => {
return new RecipeImplementation(originalImplementation, {
userCollectionName: "users",
accessFaunadbTokenFromFrontend: true,
faunaDBClient: new faunadb.Client({
secret: "<SECRET>",
}),
});
},
},
}),
]
});
3️⃣ Creating a new session
On login, you would want to create a new session using the "FaunaDB reference ID" of the logged in user.
let Session = require("supertokens-node/recipe/session");
app.post("/login", async function (req, res) {
// check for user credentials..
let userId = "<FAUNADB REFERENCE ID>";
await Session.createNewSession(res, userId);
res.send("logged in");
});
4️⃣ Retrieve the Fauna user token in any API
After session verification, you can use the session.getFaunadbToken()
function in the API
let Session = require("supertokens-node/recipe/session");
app.post("/like-comment", Session.verifySession(), function (req, res) {
let userId = req.session.getUserId();
let faunaToken = await req.session.getFaunadbToken();
// query FaunaDB on behalf of the currently logged in user.
res.send(userId);
});
If using TypeScript, the type of
req.session
isSessionContainer
, imported likeimport {SessionContainer} from "supertokens-node/recipe/session/faunadb"
5️⃣ Retrieve the Fauna user token on the frontend
In order to do this, you will need to set
accessFaunadbTokenFromFrontend
totrue
when callingSession.init
on the backend.
Then on the frontend, once a user logs in, you can retrieve the JWT payload and use the key "faunadbToken"
to read the token. Here is an example
import Session from 'supertokens-auth-react/recipe/session';
let jwtPayload = await Session.getJWTPayloadSecurely();
let faunadbToken = jwtPayload["faunadbToken"];
// query FaunaDB...
import SuperTokens from 'supertokens-website';
let jwtPayload = await SuperTokens.getJWTPayloadSecurely();
let faunadbToken = jwtPayload["faunadbToken"];
// query FaunaDB...