ballingt
ballingt16mo ago

Can Convex be a backend itself?

Starting a thread here for "is Convex a backend;" the summary is - Convex functions don't run in browsers, they run on the Convex backend. - Both web browsers and other servers (like a Next.js server) can talk to Convex, generally the WebSocket-based ConvexReactClient makes sense in browsers and the ConvexHttpClient makes sense in backend servers like Next.js server components and API routes. - The code for a Convex backend can be placed in another package in a monorepo; I'll find a previous thread wiht this approach and link to it. The gist is that you need to export the API object so that it can be used in another package. - The code for a Convex backend can also be placed in an entirely separate repo but if you do this it's more difficult to use the API object. - If you're just getting started, I recommend using the same package for frontend and backend. You can keep all your convex-specific code inside the convex/ directory so it shouldn't clutter things up to much. This code is never sent to browsers or other servers talking to Convex so there's no runtime or bundle size cost to this.
6 Replies
ballingt
ballingtOP16mo ago
@niels does this address what you're asking? Yes, Convex can act as a backend by itself, this is the normal way it's used. A ConvexClient on the frontend communicates with the Convex backend. I'm not sure what a headless backend is here, but from what I could imagine that's what Convex is: it's a backend without a frontend. Regarding code organization, you can either put the convex functions in the same repository in the convex/ directory, or (more advanced, since JS packaging is hard sometimes) you can put this in a separate repo.
niels
niels16mo ago
Hi Tom, thanks for the in-depth explanation! So it would be a little overkill to have 2 Next.js instances; 1 next-backend repo that has Convex configured and API routes that return Convex's query data, and 1 next-frontend repo that calls the next-backend repo's API route? Taking performance, security etc into account
ballingt
ballingtOP16mo ago
Yep, overkill because a Next.js server that only serves API routes that just call Convex is unnecessary: Convex can communicate directly with the browser via ConvexClient and can even expose http endpoints to replace a Next.js backend server.
niels
niels16mo ago
Ok thanks! Last question, can the Convex dir be anywhere? E.g ~src/lib/convex or something
ballingt
ballingtOP16mo ago
what does ~ mean here, home directory? The convex/ directory can be mostly anywhere, you set its location in a convex.json file next to the package.json for a project.
niels
niels16mo ago
Yeah ~ is the project root, sorry

Did you find this page helpful?