October 15, 2025

Use Mongoose with Next-Auth Without an Adapter! πŸš€

Use Mongoose with Next-Auth Without an Adapter! πŸš€

title: "Use Mongoose with Next-Auth Without an Adapter!" date: "2024-02-03" description: "A clean and minimal CRUD setup using MongoDB + Next.js."

MongoDB CRUD in Next.js (App Router)

A small, readable CRUD example you can copy into any project.

1. DB Connection

// lib/db.ts
import mongoose from "mongoose";

export async function connectDB() {
  if (mongoose.connection.readyState >= 1) return;
  await mongoose.connect(process.env.MONGO_URL!);
}

2. Model

// models/Todo.ts
import { Schema, model, models } from "mongoose";
const TodoSchema = new Schema({
  title: String,
  done: Boolean,
});
export default models.Todo || model("Todo", TodoSchema);

3. API Routes

// app/api/todos/route.ts
import { NextResponse } from "next/server";
import Todo from "@/models/Todo";
import { connectDB } from "@/lib/db";
export async function GET() {
  await connectDB();
  const todos = await Todo.find();
  return NextResponse.json(todos);
}
export async function POST(req: Request) {
  await connectDB();
  const body = await req.json();
  const todo = await Todo.create(body);
  return NextResponse.json(todo);
}

4. Client Page

"use client";
import { useEffect, useState } from "react";
export default function Page() {
  const [todos, setTodos] = useState([]);
  useEffect(() => {
    fetch("/api/todos")
      .then((r) => r.json())
      .then(setTodos);
  }, []);
  return (
    <div className="p-4">
      <h1 className="text-xl font-bold mb-2">Todos</h1>
      {todos.map((t) => (
        <div key={t._id} className="border p-2 mb-1 rounded">
          {t.title}
        </div>
      ))}
    </div>
  );
}

A simple CRUD to showcase your MDX template.

Letβ€˜s do great work together

Sign up for our newsletter*

Β© 2023 NextCodez. All Rights Reserved.Privacy Policy