Skip to main content

API Routing

What is Cors?

  • C-O-R-S,cross-origin resource sharing.
  • It's a security policy that browsers have implemented to prevent websites from accessing information from servers that aren't part of the same domain.
  • So a server can implement.So what the browser will do is something called a pre-flight check,which basically means, let's say you did a fetch request in the browser.Before that fetch request, the browser will actually go to that location first and do an options check, options method.
Browser CORS Issue

Let's say you try to do a GET request.It'll first say,let me do an options request first just to see what the server is capable of.And then the server will respond with a 200 status code saying, hey, I'm cool with this request.And then the browser will do the actual request.So that's what CORS is.

  • The browser will get that back.And if it doesn't see the domain that you're on or the IP that you're on as supported, then your request will get blocked for CORS issue.So it's just a way to protect websites through the browser.
  • So as someone who's implementing a server, if you want anyone to be able to access your server, and this doesn't count like authentication.You're still gonna add authentication.This is just like just even being able to knock on your door, basically.You have to implement CORS.So you have to implement a strategy there.So CORS is a OPTIONS request.
note

If you have one server talking to another server,CORS doesn't matter cuz only browsers look for CORS.
And I think it also only matters cross-domain, right?If you're on the same app, it doesn't matter.
It only matters for cross-domain if you are on the same domain.If your API is on yourapp.com and your website is also on yourapp.com, or even app.your app.com, it probably doesn't matter.It's only for cross-origin resource sharing, so it has to be a different domain.

why do I even need APIs then if I can just do mutations with server actions, I can do server-side fetching?

Well, sometimes you're still gonna have client components that need to get data and sometimes you're still gonna have client components that need to mutate data.
So that's where API comes in is just when you just need client components todo things.And then also if your product is some third party API that needs to offer API access to other people on their apps, then yeah, you need API for them.Maybe it's not for your app.Maybe it's for other people's apps to consume, so you're gonna make an API.
So those would probably be the two use cases I think the Next.js team would say if they were here.

info
  • I think that's what they're doing based off their documentation and their recommendations.And I have to genuinely agree.
  • Other than using server actions for everything, I still think client-side API calls is probably the way to go if UI needs to be updated for now, but that could change soon, I'm sure.