In this article, I'll show you how to store subscriber information for a Next.js blog in a MongoDB database. We'll use an ODM library called mongoose
to interact with the database and create a model for subscriber data. Then, we'll use a Next.js API route to add subscriber data to the database. Let's get started!
Configure database connection
First, let's install the mongoose
package. Next, create a MongoDB Atlas Database and add the URI in an environment variable named MONGO_URI
. After that, create a config
directory. Within this directory, create a db.ts
file with the following code:
import { connect, ConnectionStates } from 'mongoose';
let isConnected: ConnectionStates;
export default async function connectDB() {
if (isConnected) return;
const db = await connect(process.env.MONGO_URI as string);
isConnected = db.connections[0].readyState;
}
In the above code, we have a connectDB
function to connect to our MongoDB database. In the function, we check if we already have a connection. If yes, we return from the function. Otherwise, we connect to the database and update the isConnected
variable. We do this check to prevent creating multiple database connections.
Create model
Next, we need a model for our subscriber data. So, let's create a models
directory. Within this directory, create a file named subscriber.ts
with the following code:
import { Schema, model, models } from 'mongoose';
const subscriberSchema = new Schema(
{
name: {
type: String,
trim: true,
required: [true, 'Please provide a name'],
},
email: {
type: String,
trim: true,
lowercase: true,
required: [true, 'Please provide a name'],
},
},
{
timestamps: true,
}
);
export default models.Subscriber || model('Subscriber', subscriberSchema);
In this code, we've created a subscriberSchema
using the Schema
class from mongoose
. The schema is similar to what you would create in a Node.js app. However, what's important here is how we export the model.
In the last line, we export models.Subscriber
, which means exporting the Subscriber
model if it already exists. Otherwise, create and export one. We do this to prevent creating multiple instances of a model.
Add subscriber data to the database
Now, let's use the connectDB
function and the Subscriber
model to add subscriber data to the database using a Next.js API route. To do this, within the api
directory, let's create a file named subscriber.ts
with the following code:
import connectDB from '@config/db';
import Subscriber from '@models/subscriber';
import type { NextApiRequest, NextApiResponse } from 'next';
type SubscribePayload = {
name: string;
email: string;
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'POST') {
const { name, email }: SubscribePayload = req.body;
if (!name || !email) {
return res.status(400).json({ message: 'All fields are required' });
}
try {
await connectDB();
const subscriber = await Subscriber.findOne({ email }).lean();
if (!subscriber) {
await Subscriber.create({ name, email });
return res.status(201).json({ message: 'Successfully subscribed' });
}
res.status(200).json({ message: 'Already subscribed' });
} catch (err) {
console.log(err);
res.status(500).json({ message: 'Something went wrong' });
}
} else {
res.setHeader('Allow', ['POST']);
res.status(405).json({ message: `Method ${req.method} not allowed` });
}
}
In this above code, we have a handler that accepts a POST
request. In the handler, the first thing we do is make sure that the request method is POST
. Then we destructure the data from the request body and validate it, making sure all the required fields are provided.
After that, we start a try...catch
block to perform the asynchronous operations. In the block, we call the connectDB
function to create a connection to the database. Next, we check if the subscriber already exists in the database. If it doesn't, we add the subscriber and return the response 'Successfully subscribed'. Otherwise, we return the response saying 'Already subscribed'.
That's it. You can now use the /api/subscriber
endpoint to save subscriber data to a MongoDB database. Hope you've learned a thing or two from this article. Please share this content with others who might also find it useful. Cheers!