Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/dev0302/nextjs-project-1/llms.txt

Use this file to discover all available pages before exploring further.

Retrieve all anonymous messages that have been sent to the currently authenticated user. The route uses a four-stage MongoDB aggregation pipeline to unwind, sort, and regroup the embedded messages array so results always arrive in newest-first order. If the user has no messages the endpoint returns an empty array — it never returns 404 for an empty inbox.

Method and URL

GET /api/get-messages

Authentication

Required. The request must carry a valid NextAuth JWT session cookie. The server calls getServerSession(NEXT_AUTH_CONFIG) to verify the caller’s identity. Unauthenticated requests receive a 401 response.

Request Parameters

This endpoint accepts no query parameters and no request body.

How It Works — The Aggregation Pipeline

Because messages are stored as an embedded array inside the User document, a plain findById cannot sort the subdocuments efficiently. The route uses a four-stage pipeline:
const userId = new mongoose.Types.ObjectId(user._id); // string → ObjectId

const userMessages = await UserModel.aggregate([
  // Stage 1: isolate the target user's document
  { $match: { _id: userId } },

  // Stage 2: flatten — each message becomes a temporary top-level document
  { $unwind: "$messages" },

  // Stage 3: sort flattened messages newest-first
  { $sort: { "messages.createdAt": -1 } },

  // Stage 4: reassemble into a single document with a sorted messages array
  { $group: { _id: "$_id", messages: { $push: "$messages" } } },
]).exec();
The result of .aggregate() is always an array; the actual messages live at userMessages[0].messages.
String ID → ObjectId conversion is mandatory inside aggregation pipelines. NextAuth stores _id as a plain string in the session object. Mongoose auto-converts strings to ObjectId in methods like findById, but it does not do so inside aggregate. Without new mongoose.Types.ObjectId(user._id), the $match stage finds zero documents and the response is always an empty array — even when messages exist.

curl Example

# The session cookie is managed automatically by the browser.
# When testing with curl, pass the cookie explicitly.
curl -X GET https://your-domain.com/api/get-messages \
  -H "Cookie: next-auth.session-token=<your-session-token>"

Responses

200 — Success

Returned whether the user has messages or not. An empty inbox returns messages: [], not a 404.
{
  "success": true,
  "messages": [
    {
      "_id": "6650a1f2e4b0c123456789ab",
      "content": "Your talk at the conference was genuinely inspiring!",
      "createdAt": "2024-05-24T10:30:58.000Z"
    },
    {
      "_id": "6650a1f2e4b0c123456789aa",
      "content": "Great work on the open-source project.",
      "createdAt": "2024-05-23T08:14:22.000Z"
    }
  ]
}
Empty inbox:
{
  "success": true,
  "messages": []
}

401 — Not Authenticated

No valid session cookie was present.
{
  "success": false,
  "message": "Not Authenticated"
}

500 — Internal Server Error

An unexpected error occurred during the aggregation.
{
  "success": false,
  "message": "An unexpected error occurred while fetching messages"
}

Response Fields

success
boolean
true on a successful fetch (including an empty inbox); false on any error.
messages
array
Array of message objects belonging to the authenticated user, sorted newest-first. Present only on a 200 response.
messages[]._id
string
MongoDB ObjectId of the individual message, serialised as a hex string. Use this value as messageId when calling PATCH /api/delete-message.
messages[].content
string
The text body of the anonymous message.
messages[].createdAt
string
ISO 8601 timestamp set by the server at the moment the message was received (e.g. "2024-05-24T10:30:58.000Z").
The $unwind stage silently drops users who have zero messages, which is why the route explicitly checks userMessages.length === 0 and returns { success: true, messages: [] } rather than falling through to a 500.

Build docs developers (and LLMs) love