Next.js Discord

Discord Forum

What is the most efficient way to make RESTful queries using NextJS 13?

Unanswered
Black-throated Sparrow posted this in #help-forum
Open in Discord
Black-throated SparrowOP
Initially I was going to create a separate backend using Express and Node.js, however - in the spirit of embracing NextJS's serverless architecture - I decided to use Supabase as my BaaS. Currently, I am querying my database within my Events.tsx component as follows:

const Events = () => {
  const [events, setEvents] = useState<any[]>([]);

  useEffect(() => {
    const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || '';
    const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || '';

    const supabase: SupabaseClient = createClient(supabaseUrl, supabaseKey);

    async function fetchEvents() {
      const { data, error } = await supabase.from('events').select('*');
      if (error) {
        console.error('Error fetching events:', error);
      } else {
        setEvents(data || []);
      }
    }

    fetchEvents();
  }, []);

As a result of this, as you can expect, I have to render this component as a client-side component by using the "use client" keyword. If I have to do this for all components that I need to fetch data for, then would that not make NextJS's principle of using SSR whenever possible for efficiency redundant? I can understand needing to use the useEffect hook for submitting forms and the use of client side components there, however this feels like I'm unnecessarily making this component client-side.

Surely there must definitely a better way to do this that involves fetching and rendering the data on the server instead of the client, however I'm not seeing it anywhere. My confusion is exacerbated by the weird position that NextJS currently finds itself in with server actions being in alpha and scarce documentation regarding how APIs should work with the new app router (as well as, to that extent, how to efficiently make API calls).

Any help and guidance will make my journey towards creating a functional backend for my project much easier.

Thank you all in advance!

51 Replies

Black-throated SparrowOP
I also read somewhere that creating a separate backend using Express + Node.js will be inefficient for NextJS. Can someone validate this and, if this is the case, why? I apologise for my primitive understanding of NextJS as someone who's just coming from vanilla React haha
It's from John from Supabase
I use Supabase everyday but not through their sdk. I use prisma/drizzle to query db from server side code. But using supabase sdk is fine too 😉
Even if it's alpha: I use server action to mutate, I use server component to query.
If i need some client side query, i would use supabase sdk like before (nothing change from a vanilla react app)
Black-throated SparrowOP
@rphlmr 🫡 Yep that helps a lot, thank you so much! I'll do the tutorial then utilise what I've learned my personal project
As a final question, if I may, I'm a frontend developer who's trying to transition into fullstack with NextJS 13 and the fact that it facilitates backend development so well; how much would you recommend I read up on databases, SQL and really getting to grips with the principle of REST and CRUD?
SQL will always be a good bet. Can be used for many things later (complex dashboard queries, stats, etc).

Principle of REST helps to communicate with other developers. Tight it with CRUD because they go together (in many cases).
Create #Unknown Channel REST Post
Read #Unknown Channel Get
Update #Unknown Channel Put/Patch
Delete #Unknown Channel Delete

Do not stress yourself with everything at the same time.
With nextjs you'll not probably do much Rest (if needed, api route is what you would use to expose a rest api to some consumer/mobile app. Your nextjs server will become a rest api. That's really cool to start with that before thinking to evolve to something else).
Golden-winged Warbler
If you are trying to move to backend, then I do not think building with Next makes sense. They have made some tradeoffs that take it away from the way backends are built. Next focus is very much React. With backends, you will be making APIs, and by comparison, next is not an ideal choice. In many ways, Next does not want you to have an API, rather skip it and talk directly to the same things the API would from server components / actions.

You should def look into things like SQL and CRUD, but also consider that most backend systems, those that underlie our computing infra, are rarely in JS/TS. More typical are other languages like Go, Rust, Java, .Net for purely backend services. Also consider many people will probably still have an API with their Next apps so that they can also provide their users with an API while also using it for the frontend.
It can very well make sense to stick with express for the time being for your backend, if only to remove the extra effort in learning a new language. But most BE developers/teams I know loath JS/TS ecosystem
You can achieve this goal with api routes that expose the same function you'll use on your server component.
If you are a solo developer or a small team, you'll have a hard time to maintain many thing.

Starting all in Nextjs and then moving parts in dedicated backend is something smooth. No need to premature architecture to test the market.

If you are a lead dev in a big team, don't force them if they are not js/ts people. Let them make an api with their favourite tool and consume them from your nextjs backend (BFF pattern) like you would consume your db directly.
In the end it's just a datasource swap 😄
Nextjs is like php for js people :p
@Golden-winged Warbler It can very well make sense to stick with express for the time being for your backend, if only to remove the extra effort in learning a new language. But most BE developers/teams I know loath JS/TS ecosystem
Black-throated SparrowOP
If applies to full-stack development as well then please do let me know and I'll go the traditional route with a stack like PERN
Golden-winged Warbler
If you are doing full-stack, I do like a full-stack JS/TS to go with it. As @rphlmr 🫡 said, the difference in your server components is quite minimal. Often the decision can be quickly made based on if you want to expose (or not) and API to your users, also migrating between them should be low, but tedious, effort
I can see Next (server components really) becoming popular because you can avoid an API and thus people cannot scrape your platform or similar. I am just frustrated with the backend story for next...
If you work for clients like mine, you'll rebuilt the same thing at least 3 times 😂
@rphlmr 🫡 If you work for clients like mine, you'll rebuilt the same thing at least 3 times 😂
Golden-winged Warbler
that sounds good for (your) business
@Golden-winged Warbler If you are doing full-stack, I do like a full-stack JS/TS to go with it. As <@435129720326062092> said, the difference in your server components is quite minimal. Often the decision can be quickly made based on if you want to expose (or not) and API to your users, also migrating between them should be low, but tedious, effort
Black-throated SparrowOP
This is noted, I'm currently a uni student going into my second year and I'm hoping to build some personal projects that will hopefully help me apply to some internships at the end of the summer. Having said that, if the way NextJS abstracts backend development will detriment my application rather than benefit it then I'll definitely go out of my way to learn how to get good with a separate backend as well
I'd understand if that's the case too considering the fact that NextJS 13 is basically brand new, so there aren't many business that are using it yet
And even less that would be willing to transition their entire existing infrastructure to it
Golden-winged Warbler
React has Next as the first option, which is why I'm exploring it
Most important thing: build build build. Practice ;). When i recruit, i prefer people with a good mind and who like what they are doing.
@Black-throated Sparrow And even less that would be willing to transition their entire existing infrastructure to it
Golden-winged Warbler
IRL, no one makes huge sweeping changes like this. They typically try out a new tech on a single project, and then a wider migration will take years
@rphlmr 🫡 Most important thing: build build build. Practice ;). When i recruit, i prefer people with a good mind and who like what they are doing.
Golden-winged Warbler
this, also learn, learn, learn, and try things out. I like to hire people who demonstrate curiosity and ability to learn new tools quickly
Become T shaped as they say
Tech changes every 6 month on js world lol. Master principles over flavour-of-the-moment tech and you will be fine
Golden-winged Warbler
Though I think becoming π shaped will make you more well rounded 🤣
with nextjs and remix we are at a time where boundaries between front and back are close
@Golden-winged Warbler this, also learn, learn, learn, and try things out. I like to hire people who demonstrate curiosity and ability to learn new tools quickly
Black-throated SparrowOP
Yeah that's the plan, I have a bunch of projects that I want to learn with one main thing that I want to take away from all of them. Like for the one I'm currently doing it's literally just so that I can learn creating a full-stack project using NextJS haha, I love being able to point at something and say that I'm now better at that then I was before
Golden-winged Warbler
A good place to find intersting projects is by talking to professors, many will have research projects & funding. I didn't pay for any of my graduate / phd work, got started as an undergrad
Black-throated SparrowOP
That being said, I will make a project with Express and Node if it will be worthwhile for my learning but the learning curve is way higher 🥲
@Black-throated Sparrow That being said, I will make a project with Express and Node if it will be worthwhile for my learning but the learning curve is way higher 🥲
then you will understand why old hangry men like me are somewhat excited by server actions and server components lol
Black-throated SparrowOP
The only thing is that I can't really think of a project in which I'd be using that stack over this current combination because it already works so nicely XD
I only have experience in front end and when I read about SSR and server components I started crying thinking that this is the most revolutionary thing I've seen in my life
@Black-throated Sparrow The only thing is that I can't really think of a project in which I'd be using that stack over this current combination because it already works so nicely XD
Black-throated SparrowOP
I would literally just find myself learning express and node for the sake of learning express and node
Black-throated SparrowOP
Prisma on the other hand... yum
@rphlmr 🫡 create a simple api like a pizza ordering api loo
Black-throated SparrowOP
Hahaha real
That would be a good idea actually, I might build a couple APIs
Without using that API in a website
That's actually a great idea now that I think about it lol
(Don't go ahead and tell me that NextJS does it better XD)
challenge yourself and proctect this api with an authorization header 😈
Black-throated SparrowOP
I'll get back to it now, but thanks for all the help guys it's much appreciated!
@Black-throated Sparrow I only have experience in front end and when I read about SSR and server components I started crying thinking that this is the most revolutionary thing I've seen in my life
Golden-winged Warbler
everything old is new again, we did things like this before there were frontend frameworks
A great place to use an API with next is for things like webhooks, that are primarily driven by events outside of the webapp, but which the webapp will present infromation about the things webhooks act on. Webhooks will want to make a request to your services via an API, which can use the same prisma client your app uses (ideally, I haven't tried this with next yet, so the details for this are still unknown to me)