This blog is for you if you want to learn how to use GraphQL and MongoDB to construct secure APIs. This blog post will explain how to establish a schema, query, and resolvers, and use JWT tokens to authenticate requests inside of a GraphQL context.
GraphQL is an open-source query language that facilitates data retrieval from databases. It is not an ORM; rather, it is used in conjunction with ORMs to provide precise responses to client requests.
There is just one endpoint for GraphQL, which is /GraphQL, and to obtain the needed data, you must pass a query.
Instead of interacting with the database, GraphQL queries the information that the ORM has returned.
To understand how to develop secure APIs using GraphQL, let’s look at an example where a user may add, edit, and remove products from a database—but only if he is authorized.
Related read: What is GraphQL? Learn How GraphQL Is Revolutionizing API Development
npm i @apollo/server bcrypt graphql jsonwebtoken mongoose
export const typeDefs = `#graphql
interface CreateUser{
email:String,
password:String,
fullName:String
}
interface User{
email:String,
fullName:String,
id:String
}
type CreateUserMutationResponse{
id:String
password:String,
accessToken:String,
refreshToken:String,
message:String,
}
type Mutation{
createUser(email:String,password:String,fullName:String):CreateUserMutationResponse
}
`;
In our user schema, we have a createUser mutation function that creates a user, saves them in the database, and gives us the access token we need to subsequently validate the user.
import { User } from "../../models/userModel.js";
import { accessToken, refreshToken } from "../../utils/jwtAuthentication.js";
import bcrypt from "bcrypt";
export const resolvers = {
Mutation: {
createUser: async (_, { email, password, fullName }, {}) => {
try {
const hashPassword = await bcrypt.hash(password, 10);
const user = await User.create({
email,
password: hashPassword,
fullName,
});
await user.save();
const userAccessToken = accessToken<any>({
id: user._id.toHexString(),
email,
time: new Date(),
});
const userRefreshToken = refreshToken<any>({
email,
time: new Date(),
});
return {
id: user._id.toHexString(),
password: hashPassword,
accessToken: userAccessToken,
refreshToken: userRefreshToken,
message: "User created..!",
};
} catch (error) {}
},
},
};
import dotenv from "dotenv";
import jwt from "jsonwebtoken";
dotenv.config();
export const accessToken = function <T>(data: T) {
const jwtSecretKey = process.env.JWT_SECRET_KEY;
return jwt.sign(data, jwtSecretKey, { expiresIn: "30d" });
};
export const refreshToken = function <T>(data: T) {
const jwtSecretKey = process.env.JWT_SECRET_KEY;
return jwt.sign(data, jwtSecretKey, { expiresIn: "30d" });
};
import { Schema, model } from "mongoose";
const userSchema = new Schema(
{
email: { type: String, required: true },
password: { type: String, required: true },
fullName: { type: String, required: true },
},
{ timestamps: true }
);
export const User = model("User", userSchema);
We will use this user model to save the user’s data in our MongoDB database.
export const typeDefs = `#graphql
interface Product{
name:String,
company:String,
price:Int
}
input ProductInput{
name:String,
company:String,
price:Int
}
type AddProductMutationResponse{
id:String
message:String,
}
type Mutation{
addProduct(input:ProductInput):AddProductMutationResponse
}
`;
import { Schema, model } from "mongoose";
const productSchema = new Schema(
{
name: { type: String, required: true },
company: { type: String, required: true },
price: { type: String, required: true },
},
{ timestamps: true }
);
export const Product = model("Product", productSchema);
import { Product } from "../../models/productModel.js";
export const resolvers = {
Mutation: {
addProduct: async (_, { input }, { decodedToken }) => {
try {
if (!decodedToken.id) {
throw new Error("You are not authorized to perform this action.");
}
const product = await Product.create({
name: input.name,
company: input.company,
price: input.price,
});
await product.save();
return {
id: product._id.toHexString(),
message: "Product added...",
};
} catch (error) {
return error;
}
},
},
};
A user may only add a product to the database if he is authorized. We can determine if the user is authorized by accessing the token in the fourth parameter of our resolver function. If the token lacks the ID, we will throw an error.
import { makeExecutableSchema } from "@graphql-tools/schema";
import { typeDefs as bookTypeDefs } from "./book/schema.js";
import { typeDefs as userTypeDefs } from "./user/schema.js";
import { resolvers as bookResolvers } from "./book/bookResolvers.js";
import { resolvers as userResolvers } from "./user/userResolvers.js";
import { typeDefs as productTypeDefs } from "./product/schema.js";
import { resolvers as productResolvers } from "./product/productResolver.js";
export const graphqlSchema = makeExecutableSchema({
typeDefs: [bookTypeDefs, userTypeDefs, productTypeDefs],
resolvers: [bookResolvers, userResolvers, productResolvers],
});
DB Connection:
import mongoose from "mongoose";
import dotenv from "dotenv";
dotenv.config();
//DB uri
var uri = `${process.env.DB_URI}${process.env.DB}`;
mongoose.connect(uri);
export const connection = mongoose.connection;
Server:
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
import { graphqlSchema as schema } from "./modules/index.js";
import { connection } from "./utils/dbConnection.js";
import { getUserFromToken } from "./utils/getUserFromToken.js";
import { GraphQLError } from "graphql";
//Checking DB connection here
connection.once("open", function () {
console.log("MongoDB database connection established successfully");
startServer();
});
async function startServer() {
const server = new ApolloServer({
schema,
});
const { url } = await startStandaloneServer(server, {
listen: { port: 4000 },
context: async ({ req, res }: any) => {
const token = req.headers.authorization;
if (token) {
var decodedToken = await getUserFromToken(token);
if (!decodedToken) {
throw new GraphQLError(
"You are not authorized to perform this action.",
{
extensions: {
code: "FORBIDDEN",
},
}
);
}
return { decodedToken };
}
return {};
},
});
console.log(`🚀 Server ready at: ${url}`);
}
Take note that we are utilizing the context function to get the user ID from the token.
To work with huge queries and query just data that is truly needed, GraphQL is, in my view, the finest tool. Combining it with JWT tokens for secure endpoints is the icing on the cake. In this blog, we showed how to utilize GraphQL context to authenticate a user before making any requests.
The team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork