Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access env variables next.js [duplicate]

I'm creating an app with Next.js and Supabase. When I create the client in /utils/supabase-client.js, it throws the error that Error: supabaseUrl is required..

Here is my file:

import { createClient } from '@supabase/supabase-js'

const supabaseUrl = process.env.SUPABASE_PROJECT_URL
const supabaseAnonKey = process.env.SUPABASE_ANON_KEY

export const supabase = createClient(supabaseUrl, supabaseAnonKey)

Of course my env variables are okay and defined in a .env file like this:

SUPABASE_PROJECT_URL=myRealSupabaseProjectUrl
SUPABASE_ANON_KEY=myRealSupabaseAnonKey

It should be clarified that I'm using other env variables (like contentful API keys) and they work fine. And if I log in /utils/supabase-client.js the supabaseUrl and supabaseAnonKey the log works and in shows the right values. It seems that the problem is with the createClient() I think

Then, in a template page, I use it like this:

import { supabase } from '../lib/supabase-client'

and inside the component:

  const handleViews = useCallback(async () => {
    try {
      const { data } = await supabase
        .from('Page Views')
        .select()
        .eq('slug', query)
      try {
        // @ts-ignore
        if (data?.length < 1 || !data) {
          return await supabase
            .from('Page Views')
            .insert({ slug: query, views: 1 })
        } else {
          const views = data[0]?.views
          return await supabase
            .from('Page Views')
            .update({ slug: query, views: views + 1 })
        }
      } catch (err) {
        console.log(err, 'error')
      }
    } catch (err) {
      console.log(err, 'error')
    }
  }, [query])

I repeat: this works absolutely fine if I change the process.env.SUPABASE_PROJECT_URL and process.env.SUPABASE_ANON_KEY for their absolute values.

Thanks

like image 421
Emiliano Avatar asked Jun 29 '26 05:06

Emiliano


1 Answers

When using the Supabase client in a client-side component, you need to prefix your env vars with NEXT_PUBLIC, e.g.

NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=
SUPABASE_SERVICE_ROLE_KEY=

Note, do not prefix your SERVICE_ROLE key with NEXT_PUBLIC as it needs to be kept secret and should only be used in secure server-side environments (e.g. API routes, SSR pages) but never exposed client-side.

By pre-fixing your env var with NEXT_PUBLIC Next.js will replace the env var with the variable value at build time and therefore expose it in your generated HTML, see https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser

like image 168
thorwebdev Avatar answered Jun 30 '26 19:06

thorwebdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!