Our home page HTML will contain a form to create posts and a container to display posts.
But first we need to check a user is logged in.
Auth Check
We will connect index.html to js/posts.js:
<script type="module" src="js/posts.js"></script>
In js/posts.js:
import { supabase } from "./supabase.js";
import { checkAuth, logout } from "./auth.js";
checkAuth();
After the imports and before any other code, call checkAuth. We don’t want any other code to run if we are not logged in.
Handling the Create Post Form
We need a title input and a content textarea:
<form>
<input name="title" required />
<textarea name="content" required></textarea>
<button>Submit</button>
</form>
In js/posts.js:
const postForm = document.querySelector("form");
postForm.addEventListener("submit", async function (e) {
e.preventDefault();
const form = e.target;
const title = form.title.value.trim();
const content = form.content.value.trim();
try {
const { error } = await supabase.from("posts").insert([{ title, content }]);
if (error) {
// handle error
}
// display a success message
form.reset();
} catch (error) {}
});
Key Concepts
supabase.from("posts")targets the posts table..insert([{ title, content }])creates a new row with the form data.- The
user_idis automatically added by our RLS policy (usingauth.uid()). - Supabase handles the database connection and SQL generation.
- The insert returns an
errorif something goes wrong. Remember to always display error messages to users. - Display a message on successful insert, too, and clear the form.
Create a post with the form, then view the post in Supabase:
- Click Database in the menu.
- Click Tables.
- Select View in Table Editor from the menu button (three vertical dots).