add supabase in next.js in javascript

To add Supabase in Next.js using Javascript, follow the steps below:

  1. Install Supabase client package in your Next.js project.
index.tsx
npm install @supabase/supabase-js
34 chars
2 lines
  1. Create a configuration file where you can initialize your Supabase client with your project settings. You can name it supabase.js and place it inside a lib directory at the root of your project.
import { createClient } from '@supabase/supabase-js';

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;

export const supabase = createClient(supabaseUrl, supabaseAnonKey);
249 chars
7 lines
  1. In your Next.js page, import the supabase client and use it to interact with your Supabase database.
import { supabase } from '../lib/supabase';

export default function MyPage() {
  const { data, error } = useSWR('/api/get-data', fetcher);
  
  if (error) return <div>Failed to load</div>;
  if (!data) return <div>Loading...</div>;
  
  const { id, title, body } = data;

  const updateData = async () => {
    const { data, error } = await supabase
      .from('my-table')
      .update({ title, body })
      .match({ id });
    
    if (error) console.log('error', error);
  };

  return (
    <div>
      <h1>{title}</h1>
      <p>{body}</p>
      <button onClick={updateData}>Update Data</button>
    </div>
  );
}
621 chars
28 lines

Note that the supabaseUrl and supabaseAnonKey values are pulled from environment variables, which should be defined in a .env.local file at the root of your project.

NEXT_PUBLIC_SUPABASE_URL=https://your_supabase_url.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
116 chars
3 lines
  1. Test your Supabase integration by running your Next.js project and verifying that you can read and write data to your Supabase database.

gistlibby LogSnag