fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← Back end

Back end / 5 MIN READ

Step 1: Set Up Your Supabase Project

Implementing user authentication with Supabase is straightforward, and adding Google authentication alongside traditional email/password authentication pro

From the original Fervor library. Examples may use older package versions.

Implementing user authentication with Supabase is straightforward, and adding Google authentication alongside traditional email/password authentication provides flexibility for users. Here’s a step-by-step tutorial on setting up a basic webpage where users can post comments using either Google or email authentication through Supabase.

Step 1: Set Up Your Supabase Project

First, ensure you have a Supabase account and a project set up. If you need to set up a project, refer to the steps in earlier messages about creating a new Supabase project.

Step 2: Configure Authentication

Enable Google Authentication

  1. Go to the Supabase dashboard and select your project.
  2. Navigate to Authentication > Settings.
  3. In the External OAuth Providers, find Google and enable it.
  4. You’ll need to set up OAuth credentials in the Google Developer Console (follow Supabase’s provided links and instructions to obtain the Client ID and Client Secret).
  5. Enter these credentials back in your Supabase project settings.

Set Up Email Authentication

This is usually enabled by default, but you can check under Authentication > Settings to confirm and configure things like email templates.

Step 3: Create the Database Tables

You’ll need at least two tables: users and comments.

-- Create a users table
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    username VARCHAR(255),
    email VARCHAR(255) UNIQUE NOT NULL
);

-- Create a comments table
CREATE TABLE comments (
    comment_id SERIAL PRIMARY KEY,
    user_id UUID REFERENCES users(id),
    content TEXT NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

Step 4: Implement Authentication on Your Website

Assuming you’re using HTML, CSS, and JavaScript for your webpage:

HTML Setup

Create a simple HTML form for login and posting comments.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Comment Page</title>
</head>
<body>
    <div id="user-auth">
        <button onclick="signInWithGoogle()">Sign In with Google</button>
        <button onclick="signInWithEmail()">Sign In with Email</button>
    </div>
    <div id="post-comment" style="display:none;">
        <textarea id="comment-box" placeholder="Write a comment..."></textarea>
        <button onclick="postComment()">Post Comment</button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js"></script>
    <script src="app.js"></script>
</body>
</html>

JavaScript Setup

Create a file named app.js for handling the authentication and posting comments.

const supabaseUrl = 'your-supabase-url';
const supabaseAnonKey = 'your-anon-key';
const supabase = createClient(supabaseUrl, supabaseAnonKey);

async function signInWithGoogle() {
    const { user, error } = await supabase.auth.signIn({
        provider: 'google'
    });
    if (user) console.log('Logged in: ', user);
    if (error) console.error('Error logging in: ', error);
}

async function signInWithEmail() {
    const email = prompt('Please enter your email:');
    const { user, error } = await supabase.auth.signIn({ email });
    if (user) console.log('Check your email for the login link!');
    if (error) console.error('Error logging in: ', error);
}

async function postComment() {
    const content = document.getElementById('comment-box').value;
    const { data, error } = await supabase
        .from('comments')
        .insert([{ user_id: supabase.auth.user().id, content: content }]);
    if (data) {
        console.log('Comment posted:', data);
        document.getElementById('comment-box').value = ''; // clear the textarea
    }
    if (error) console.error('Error posting comment: ', error);
}

supabase.auth.onAuthStateChange((event, session) => {
    const authDiv = document.getElementById('user-auth');
    const commentDiv = document.getElementById('post-comment');
    if (session) {
        authDiv.style.display = 'none';
        commentDiv.style.display = 'block';
    } else {
        authDiv.style.display = 'block';
        commentDiv.style.display = 'none';
    }
});

Step 5: Test Your Setup

  • Load your HTML file in a browser.
  • Try signing in using both Google and email.
  • Once authenticated, try posting comments.

This basic tutorial covers setting up authentication and using it to control access to posting comments. You can expand this by

Bonus Next.js Components

Absolutely! Let’s translate that functionality into a Next.js application, which will use Supabase for authentication with Google and email, and allow users to post comments. Next.js is a popular React framework that provides server-side rendering and static site generation, making it a great choice for robust applications.

Step 1: Setup Your Next.js Project

First, you need to create a new Next.js project if you haven’t done so yet. Open your terminal and run the following commands:

npx create-next-app my-supabase-app
cd my-supabase-app

Step 2: Install Supabase Client

Next, install the Supabase JavaScript client:

npm install @supabase/supabase-js

Step 3: Initialize Supabase Client

Create a .env.local file in your Next.js project root and add your Supabase URL and anon key:

NEXT_PUBLIC_SUPABASE_URL=your-supabase-url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-supabase-anon-key

Create a file utils/supabaseClient.js to initialize the Supabase client:

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

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

const supabase = createClient(supabaseUrl, supabaseAnonKey);

export default supabase;

Step 4: Creating Components

Authentication Component

Create components/Auth.js to handle user sign-in:

import supabase from '../utils/supabaseClient'

const Auth = () => {
    const handleLogin = async (provider) => {
        const { error } = await supabase.auth.signIn({ provider });
        if (error) console.error('Login error', error.message);
    };

    return (
        <div>
            <button onClick={() => handleLogin('google')}>Sign in with Google</button>
            <button onClick={() => handleLogin('email')}>Sign in with Email</button>
        </div>
    );
};

export default Auth;

Comment Component

Create components/Comments.js for posting comments:

import { useState } from 'react';
import supabase from '../utils/supabaseClient'

const Comments = () => {
    const [comment, setComment] = useState('');

    const postComment = async () => {
        const { data, error } = await supabase
            .from('comments')
            .insert([{ content: comment, user_id: supabase.auth.user().id }]);
        if (error) console.error('Error posting comment', error);
        else {
            console.log('Comment posted', data);
            setComment(''); // clear the input after posting
        }
    };

    return (
        <div>
            <textarea value={comment} onChange={(e) => setComment(e.target.value)} placeholder="Write a comment..."></textarea>
            <button onClick={postComment}>Post Comment</button>
        </div>
    );
};

export default Comments;

Step 5: Update the Main Page

Modify the pages/index.js to use the Auth and Comments components:

import Auth from '../components/Auth';
import Comments from '../components/Comments';
import supabase from '../utils/supabaseClient';

export default function Home() {
    const user = supabase.auth.user();

    return (
        <div>
            {!user ? <Auth /> : <Comments />}
        </div>
    );
}

Step 6: Running Your Next.js App

Finally, run your Next.js app to see everything in action:

npm run dev

Open http://localhost:3000 in your browser to test signing in with Google or email and posting comments.

Conclusion

This setup in a Next.js environment provides a good foundation for building applications with user authentication and interactive features like commenting. Using components for authentication and comments makes your application modular and easy to expand or modify.

Keep your curiosity going.Explore more Back end →
287 TUTORIALS · 22 TOPICSREADY