how can I use a keystonejs v6 inside a nestjs app?

219 Views Asked by At

Suppose I already have a Keystone setup installed in a folder, and now I want to extend this app by adding some REST API endpoints to it. The standard way to achieve this is by using extendExpressApp, but it doesn't work when all my development tools are in a different framework like NestJS. In order to run my queries and perform other actions, I need to incorporate KeystoneJS as a library inside my NestJS framework. (I can set up the NestJS server inside or beside or as a parent folder of the keystone setup but I don't think it is a best practice to mix two different frameworks in the same folder).

There are a few workarounds available:

One option is to use a separate Prisma client to work with the same configuration, but this approach doesn't handle the access controls defined within Keystone. Another option is to use a GraphQL client to access the Keystone server as a client. However, in my opinion, this approach is not very efficient in terms of both development and performance, especially when dealing with a codebase that contains numerous GraphQL queries.

1

There are 1 best solutions below

0
On

I haven't tried this specifically but I think I can point you in the right direction.

When you use the Keystone CLI (eg. keystone start, keystone dev, etc.), internally Keystone is just creating a Apollo server, wrapping Prisma to connect to the DB, creating an Express app, a NextJS app and plugging in a few routes. What you need to do is basically build your own start command that does (some of) the same stuff but plugs the resultant server into your NestJS server.

I have no NestJS experience so can't speak to specifics but have a look at the standard keystone start command and the createExpressServer function. They're only ~150 lines of code combine. You can see, for example, where Keystone creates the Apollo server and plugs it to the /api/graphql route (by default) then, back in start, where we spin up the NextJS app for the AdminUI.

Keystone apps were always intended to be composable in this way – the CLI just makes it easier out of the box. There should be nothing stopping you from using whichever of these building blocks you'd like to create an app with whatever HTTP server/framework/configuration you need.

I have a previous answer to a question about customising the default express app that might also be helpful.