add supabase to next.js in javascript

To add Supabase to a Next.js project in JavaScript, follow these steps:

  1. Install the supabase package using npm or yarn.

    npm install @supabase/supabase-js
    
    34 chars
    2 lines

    or

    yarn add @supabase/supabase-js
    
    31 chars
    2 lines
  2. Create a supabase.js file in your lib folder, where you can create a connection to your Supabase account and export it for use throughout your app.

    index.tsx
    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

    Note: Make sure to create a .env.local file in your root directory and add your Supabase URL and anonymous key.

    NEXT_PUBLIC_SUPABASE_URL=your-supabase-url
    NEXT_PUBLIC_SUPABASE_ANON_KEY=your-supabase-anon-key
    
    96 chars
    3 lines
  3. Use the supabase client instance within your application pages or components.

    index.tsx
    import { supabase } from "../lib/supabase";
    
    export default function Home() {
      const [user, setUser] = useState(null);
    
      useEffect(() => {
        const { data: authListener } = supabase.auth.onAuthStateChange(
          (event, session) => {
            setUser(session?.user ?? null);
          }
        );
    
        return () => {
          authListener.unsubscribe();
        };
      }, []);
    
      const handleLogin = async (email) => {
        const { data, error } = await supabase.auth.signIn({
          email: email,
        });
    
        console.log(data, error);
      };
    
      return (
        <div>
          <h1>Supabase + Next.js</h1>
          <p>{user ? `Logged in as ${user.email}` : "Not logged in"}</p>
          <button onClick={() => handleLogin("test@example.com")}>
            Login
          </button>
        </div>
      );
    }
    
    762 chars
    36 lines

    In this example, onAuthStateChange is used to listen for changes in the authentication state, signIn is used to authenticate a user, and the user state is used to render conditional content based on the authentication status.

That's it! You have successfully integrated Supabase into your Next.js application.

gistlibby LogSnag