@psteinroe/fastify-supabase
Version:
A Fastify plugin to use authenticated Supabase clients in your API.
85 lines (84 loc) • 2.34 kB
JavaScript
// src/fastify-supabase.ts
import createError from "@fastify/error";
import {
createClient
} from "@supabase/supabase-js";
import fp from "fastify-plugin";
var AuthorizationTokenInvalidError = createError(
"FST_SB_AUTHORIZATION_TOKEN_INVALID",
"Authorization token is invalid",
401
);
var NoUserDataFoundError = createError(
"FST_SB_NO_USER_DATA_FOUND",
"No user data found in the request. Make sure to run request.jwtVerify() before trying to access the user.",
401
);
var fastifySupabase = (fastify, opts, next) => {
const { url, serviceKey, anonKey, options } = opts;
const supabase = createClient(url, serviceKey, options);
if (fastify.supabaseClient) {
return next(new Error("fastify-supabase has already been registered"));
}
fastify.decorate("supabaseClient", supabase);
fastify.decorateRequest("_supabaseClient");
fastify.decorateRequest(
"supabaseClient",
{
getter() {
const req = this;
if (req._supabaseClient)
return req._supabaseClient;
if (req.user.role === "service_role") {
req._supabaseClient = fastify.supabaseClient;
} else if (req.user.role && req.user.role !== "anon") {
const client = createClient(url, anonKey, {
...options,
auth: {
...options?.auth,
persistSession: false
},
global: {
...options?.global,
headers: {
...options?.global?.headers,
Authorization: `Bearer ${fastify.jwt.lookupToken(req)}`
}
}
});
req._supabaseClient = client;
}
if (!req._supabaseClient) {
throw new AuthorizationTokenInvalidError();
}
return req._supabaseClient;
}
},
["user"]
);
fastify.decorateRequest(
"supabaseUser",
{
getter() {
const req = this;
if (!req.user) {
throw new NoUserDataFoundError();
}
return req.user;
}
},
["user"]
);
next();
};
var fastify_supabase_default = fp(fastifySupabase, {
fastify: "5.x",
name: "fastify-supabase",
dependencies: ["@fastify/jwt"]
});
// src/index.ts
var src_default = fastify_supabase_default;
export {
src_default as default
};
//# sourceMappingURL=index.js.map