0
0
Supabasecloud~5 mins

Environment variables and secrets in Supabase

Choose your learning style9 modes available
Introduction

Environment variables and secrets help keep important information safe and separate from your code. They make it easy to change settings without changing the code.

When you need to store API keys safely without putting them in your code.
When you want to change database connection details without editing your app.
When you deploy the same app to different places with different settings.
When you want to keep passwords or tokens hidden from public view.
When you want to update secrets without restarting or changing your app code.
Syntax
Supabase
SUPABASE_URL=your-supabase-url
SUPABASE_ANON_KEY=your-anon-key

# In Supabase dashboard, find these in Project Settings > API
Environment variables are key-value pairs stored outside your code.
Secrets like API keys should never be hardcoded or shared publicly.
Examples
Example of setting environment variables for Supabase URL and anonymous key.
Supabase
SUPABASE_URL=https://xyzcompany.supabase.co
SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Accessing environment variables in a Node.js app to connect to Supabase.
Supabase
// Using environment variables in JavaScript
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseAnonKey = process.env.SUPABASE_ANON_KEY;
How to find your Supabase URL and anon key in the dashboard.
Supabase
# In Supabase dashboard
# Go to Project Settings > API
# Find your Project URL (SUPABASE_URL) and anon key (SUPABASE_ANON_KEY)
Sample Program

This example shows how to store Supabase URL and anon key in environment variables and use them in a JavaScript app to connect securely. The getUser function fetches the current user info.

Supabase
# .env file content
SUPABASE_URL=https://xyzcompany.supabase.co
SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

// JavaScript example to initialize Supabase client
import { createClient } from '@supabase/supabase-js';

const supabaseUrl = process.env.SUPABASE_URL;
const supabaseAnonKey = process.env.SUPABASE_ANON_KEY;

const supabase = createClient(supabaseUrl, supabaseAnonKey);

async function getUser() {
  const { data, error } = await supabase.auth.getUser();
  if (error) {
    console.error('Error fetching user:', error.message);
  } else {
    console.log('User data:', data.user);
  }
}

getUser();
OutputSuccess
Important Notes

Never commit your environment files (.env) to public repositories.

Use Supabase dashboard to manage secrets safely for production.

Environment variables help keep your app flexible and secure.

Summary

Environment variables store important info outside your code.

Secrets like API keys should be kept private and secure.

Supabase dashboard lets you manage these variables easily.