Setting the file. One moment.
Chapter 07 · Firebase Data Connect
Subchapter 7.8
reference/sdk_admin_node.mdMarkdown4 KBView on GitHub
Consult this file when writing server-side code (e.g., Cloud Functions) that needs elevated privileges or needs to impersonate specific users.
impersonate parameter to run operations as a
specific user or as an unauthenticated user.undefined as the first argument (variables) to clearly indicate no
variables are being provided.@auth(level: NO_ACCESS). This ensures they
can only be called via the Admin SDK with unrestricted access.default branch to switch statements or an
else branch to handle unknown values gracefully when schemas evolve.To generate an Admin SDK, add the adminNodeSdk block to your connector.yaml:
connectorId: my-connector
generate:
adminNodeSdk:
outputDir: "./admin-sdk"
package: "@dataconnect/admin-generated"
packageJsonDir: "." # Directory containing package.jsonRun the generation command:
npx -y firebase-tools@latest dataconnect:sdk:generateUnauthenticated users can only run operations marked as PUBLIC.
import { initializeApp } from "firebase-admin/app";
import { getDataConnect } from "firebase-admin/data-connect";
import { connectorConfig, getSongs } from "@dataconnect/admin-generated";
const adminApp = initializeApp();
const adminDc = getDataConnect(connectorConfig);
const songs = await getSongs(
adminDc,
{ limit: 4 },
{ impersonate: { unauthenticated: true } }
);When using callable Cloud Functions, the authentication token is automatically verified.
import { HttpsError, onCall } from "firebase-functions/https";
import { getMyFavoriteSongs } from "@dataconnect/admin-generated";
export const callableExample = onCall(async (req) => {
const authClaims = req.auth?.token;
if (!authClaims) {
throw new HttpsError("unauthenticated", "Unauthorized");
}
const favoriteSongs = await getMyFavoriteSongs(
adminDc,
undefined,
{ impersonate: { authClaims } }
);
return favoriteSongs;
});For non-callable endpoints, you must verify the token yourself.
import { getAuth } from "firebase-admin/auth";
import { onRequest } from "firebase-functions/https";
import { getMyFavoriteSongs } from "@dataconnect/admin-generated";
const auth = getAuth();
export const httpExample = onRequest(async (req, res) => {
const token = req.header("authorization")?.replace(/^bearer\s+/i, "");
if (!token) {
res.sendStatus(401);
return;
}
let authClaims;
try {
authClaims = await auth.verifyIdToken(token);
} catch {
res.sendStatus(401);
return;
}
const favoriteSongs = await getMyFavoriteSongs(
adminDc,
undefined,
{ impersonate: { authClaims } }
);
res.send(favoriteSongs);
});Omit the impersonate parameter to run with full admin access. Only do this for
true administrative tasks.
import { upsertSong } from "@dataconnect/admin-generated";
await upsertSong(adminDc, {
title: "New Song",
genre: "Rock"
});