T
TanStack2mo ago
stormy-gold

Handling CORS in server routes

Hi, I'm looking to implement server API routes so they can be called from other origins but I'm not sure how. Is there an example I can look at?
3 Replies
eastern-cyan
eastern-cyan2mo ago
On dev, you will have to update vite.config with cors - to allow origins. Next, what ever you have on server - also has to handle CORS.
harsh-harlequin
harsh-harlequin2mo ago
Typically you would write or add a middleware (https://tanstack.com/start/latest/docs/framework/react/guide/middleware) that add different CORS headers to the response depending if you want to allow the origin or not. I think the MDN article is a really good (and comprehensive) start though: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS In the most simple of cases (allow all) you would just add one header:
{'Access-Control-Allow-Origin', '*'}
{'Access-Control-Allow-Origin', '*'}
harsh-harlequin
harsh-harlequin2mo ago
And if you haven't read it, this article by Jake Archibald is really great - and a fun read: https://jakearchibald.com/2021/cors/
How to win at CORS
The 'how' and 'why' of CORS, from start to finish.

Did you find this page helpful?