Create a serverless API with TypeScript, GraphQL and MongoDB
Posted on 20th November 2019•
Last updated on 4th December 2020
14 min read•
First Vercel will need be downloaded, installed and logged into.
The nice thing about using Vercel for development is that we don’t have to worry about manually configuring TypeScript.
Then create a folder, initialize a project in it and install
typescript as a dev dependency.
Setup the Database
To start setting up the database first go to MongoDB Atlas, create a database and get the connection URI.
If you want a more detailed explanation check out my previous guide here. Note that you can’t follow it exactly here because you can no longer create new accounts in MLab (use MongoDB Atlas instead) and that guide is for an always running server, not a serverless one.
Then install the
mongoose dependency. Since we’ll be working with TypeScript we’ll need the types for
mongoose as well.
After let’s create the model for the notes. Create a folder called
src. After that create a folder called
src. Then in that create another folder called
models and in that create the file
Start by importing
Next create an interface for the model which extends from
mongoose.Document. We’ll need to export this interface for use later as well.
After that we’ll create the schema definition.
Then define the name of the collection and the schema using schema definition.
Since we’re building a serverless API, we can’t depend on a persistent connection to database. When creating a Model we need to create it using the database connection.
To compensate for using serverless we’ll generate the Model at runtime using a function. After declaring the function, make it the default export.
After creating the Note Model, let’s look into the database connection.
Since we’re using serverless, we can’t have a persistent connection to database for every invocation of the serverless function as this would create issues with scaling.
First create the
.env file in the project root to store the MongoDB URI as
Next create the the
index.js file in
src/database and import
Then get the MongoDB URI that we included in the .env file. It can be accessed as a key in
After that declare a variable that will be used to cache the database connection between function invocations to prevent overloading the database.
Finally we need to create a function that will return a database connection. The function will first check if there is a cached connection. If there is one it will return it or else it will create a new connection and cache and return it. Be sure to export the function.
Setup the GraphQL API
First let’s install the dependencies.
Next create the folder
api in the project root and in it create the file
graphql.ts. Vercel will expose the serverless function in the file as the endpoint /api/graphql. The GraphQL function will be created using Apollo Server. Since we’re doing a serverless version we’ll be using apollo-server-micro.
apollo-server-micro and the function to create the database connection.
After that import the GraphQL Schemas and Resolvers. We’ll create these later.
Then initialize the Apollo Server and export it.
When creating a new
ApolloServer, we can define the
context option. The
context is an object which can be accessed by any of the resolvers.
This will be a good place to initialize the database connection and automatically pass it down to the resolvers.
To finish configuring we’ll set the
Setup the GraphQL Schema
src folder create the
graphql folder and in it create the
GraphQL doesn’t have a type for date and time so we’ll need a schema for those types. Create
custom.ts in the
Next we’ll setup the schema for Note.
First create the Note schema file,
note.ts in the
Then add the Note type.
After that add two Queries, one to get all Notes and one to get a specific Note.
Next add two Mutations to create new Notes and delete existing ones.
Note that we add the keyword
extendto the Query and Mutation type in the two schemas. This is because we’ll be joining all the schemas into one later.
Finally we’ll need a schema a join all the others schemas together. Create
index.ts in the
schema folder and declare and export the Link Schema in an array.
Then import the other Schemas and add them to the array.
Setup the resolvers
Since we added a custom type for dates and times in our schema, the first resolver we’ll add is for those types. Create a folder called
resolvers in the
graphql folder and in it create
Next we’ll start working on the resolver for Notes.
Start by creating
graphql, importing the required dependencies and exporting an empty object which is going to be our resolver.
Then define an object for the Queries.
When defining the function for each of the queries (or mutations or fields) there are three important parameters.
parent- If you a resolving a field of an object this parameter will contain it. We won’t be needing it in this post.
args- The arguments passed to the query or mutation.
context- The context object created when setting up the API. In our case it’ll contain the database connection.
First let’s write the resolver for
getAllNotes. Start by declaring the function.
Let’s destructure the
In the function we should create the Note model using the database connection from the context and retrieve all the Notes using it.
After that let’s add the resolver for
We can retrieve the
id argument from the second parameter.
Let’s finish of the Note resolvers by adding the resolvers for the mutations.
Now we have to connect all the resolvers together using an
index.ts file created in the
Running the API locally
To run the project locally first you need to link it to a Vercel project.
vercel dev to start the API locally.
If you visit
http://localhost:3000/api/graphql you can see the GraphQL Playground.
Deploying to Vercel
First we need to upload the database path as an Environment Variable.
Name the variable
DB_PATH and make sure you make to available for all three environments (Production, Preview and Development).
Then all that’s left to do is to deploy to Vercel.
The GraphQL Playground should be visible in the
/api/graphql route of the URL returned.
If you want a more detailed explanation into GraphQL and making a server for it, you can check out the excellent guide that I learnt from here.
Bonus: Using it in Next.js
You can create a GraphQL API endpoint in your Next.js project by putting the
graphql.ts inside the
api folder in the
The only extra step you need to do is to add this bit of code to the end of the
If you enjoyed this post please leave a like or two below!!!
Check out my latest post...Making delayed network requests in React after state changes
13th September 2021