You should start creating a View in Supabase!!
Ali Asgar L. Laut
Posted on May 22, 2024
What even are Views?
If you are new to postgres or if you are a frontend heavy developer who is currently relying on supabase to have a magic backend appearing out of nowhere, or maybe you are just someone who likes to read stuff and in that case I have something to share with you!
Start.👏 Using.👏 Views.👏
If you do not know what Views are, then here is a link from postgres documentation. Well basically I like to describe Views as a mini table for your query. That means if you have a query with a long ass complex joins statements, and it is something that you know will be needed by multiple pages on your frontend. Then VOIILAAA! encapsulate it inside a View!
What even is the Syntax?
Remember the SELECT statement from Postgres?
Well you can just add CREATE VIEW view_name AS
before the SELECT statement.
There you go! you have now created a View!
I am preaching this out for those people who are using or is planning to use Supabase since they made it very easy to use!
Once you have a view ready, you will be able to query it on your frontend like how you query a table. Real Simple!
const { data, error } = await supabase.from('user_listings').select('*')
Sweet right?
Basically you just RAW SQL'd it with VIEW style!!
Wait! There's more!
Views are really powerful especially with Supabase Auth. You can combine using auth.uid() on your query and do it like this
With this, you don't have to worry about authentication. The user_profile VIEW above will query only the authenticated user's data if the user is authenticated. That means if the user is not authenticated then they get nothing. Adding an extra security layer to your backend which is great!
Wait! There's more?
Now if we create more Views inside Supabase and use it to fetch data into your front-end application then that would mean tables will no longer be relevant for READ actions.
and the answer to that is YES! we want it this way!
This is what I plan to preach anyway. :D
If you want to create Views for fetching most of the data that you need in your frontend application. Then let's take one step further!
- Remove all READ access to your tables using Row Level Security.
- Set READ access accordingly based on user roles on the Views that you created.
Now you have another layer of security!
Ok Now I'll stop
Hopefully I convinced you to create Views in Supabase!
In conclusion, Views are great as you can store your SQL query inside it and will act as table for you to access in your frontend application. Combining with Supabase Auth, you will have a great time and will no longer worry about the user's authentication status when calling it from your frontend. Lastly, you can protect your tables by removing all READ access unto it and instead give the users access to the Views instead.
Posted on May 22, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.