Skip to content

Instantly share code, notes, and snippets.

@kluplau
Last active July 3, 2024 09:35
Show Gist options
  • Save kluplau/1f40441a424ccedd918a52624c2776a9 to your computer and use it in GitHub Desktop.
Save kluplau/1f40441a424ccedd918a52624c2776a9 to your computer and use it in GitHub Desktop.
Updated supabase.ts based on article by Andrii Shupta (https://blog.andriishupta.dev/setup-supabase-with-nestjs)
import { Inject, Injectable, Logger, Scope } from "@nestjs/common";
import { Request } from "express";
import { REQUEST } from "@nestjs/core";
import { ConfigService } from "@nestjs/config";
import { createClient, SupabaseClient } from "@supabase/supabase-js";
import { ExtractJwt } from "passport-jwt";
@Injectable({ scope: Scope.REQUEST })
export class Supabase {
private readonly logger = new Logger(Supabase.name);
private clientInstance: SupabaseClient;
constructor(
@Inject(REQUEST) private readonly request: Request,
private readonly configService: ConfigService,
) {}
getClient() {
this.logger.log("getting supabase client...");
if (this.clientInstance) {
this.logger.log("client exists - returning for current Scope.REQUEST");
return this.clientInstance;
}
this.logger.log("initialising new supabase client for new Scope.REQUEST");
this.clientInstance = createClient(
this.configService.get("SUPABASE_URL"),
this.configService.get("SUPABASE_KEY"),
{
auth: {
autoRefreshToken: true,
detectSessionInUrl: false,
},
global: {
headers: {
Authorization: `Bearer ${ExtractJwt.fromAuthHeaderAsBearerToken()(this.request)}`,
},
},
},
);
this.logger.log("auth has been set!");
return this.clientInstance;
}
}
@kluplau
Copy link
Author

kluplau commented Jul 3, 2024

Upgraded to Supabase version 2 from 1, using the upgrade guide.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment