in

Error: HTTP DELETE is not supported when trying to delete a user nextjs


I have the following page

import Head from 'next/head';
import Moment from 'moment';
import User from '@/models/user';
import Link from 'next/link';
import { useSession, getSession } from 'next-auth/client';
import { connectToDatabase } from '@/lib/mongodb';
import { IdentificationIcon, TrashIcon } from '@heroicons/react/outline';

// compontents
import Heading from '@/components/Heading';

const listUsers = ({ users }) => {
  const [session, loading] = useSession();

  const deleteUser = async (id) => {
    try {
      const res = await fetch(`/api/auth/delete/ + ${id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id })
      });

      console.log(id);

      if (res.status === 200) {
        return;
      } else {
        throw new Error(await res.text());
      }
    } catch (error) {
      console.error('An unexpected error happened occurred:', error);
    }
  };

  return (
    <>
      <Head>
        <title>Ellis Development - List Users</title>
      </Head>

      <div className="flex flex-col justify-center w-full">
        <Heading title="List Users" size="2xl" weight="bold" />

        <div className="flex flex-col mt-8">
          <div className="overflow-x-auto shadow overflow-hidden rounded-lg">
            <table className="min-w-full divide-y divide-gray-200">
              <thead>
                <tr>
                  <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    ID
                  </th>

                  <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Firstname
                  </th>

                  <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Lastname
                  </th>

                  <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Username
                  </th>

                  <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Email
                  </th>

                  <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Last login
                  </th>

                  <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Last updated
                  </th>

                  <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Admin?
                  </th>

                  <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Actions
                  </th>
                </tr>
              </thead>

              <tbody className="bg-white divide-y divide-gray-200">
                {users.map((user, userIdx) => (
                  <tr key={user._id} className={userIdx % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                    <td className="px-6 py-4 text-sm text-gray-500">{user._id}</td>
                    <td className="px-6 py-4 text-sm text-gray-500">{user.firstname}</td>
                    <td className="px-6 py-4 text-sm text-gray-500">{user.lastname}</td>
                    <td className="px-6 py-4 text-sm text-gray-500">{user.username}</td>
                    <td className="px-6 py-4 text-sm text-gray-500">{user.email}</td>

                    <td className="px-6 py-4 text-sm WH text-gray-500">
                      {Moment(user.lastLoggedIn).format('MMMM Do YYYY @ h:mma')}
                    </td>

                    <td className="px-6 py-4 text-sm text-gray-500">
                      {Moment(user.lastLoggedIn).format('MMMM Do YYYY @ h:mma')}
                    </td>

                    <td className="px-6 py-4 text-sm text-gray-500 text-center">
                      {user.admin ? '✅' : '❌'}
                    </td>

                    <td className="px-6 py-4 flex">
                      <Link href="#">
                        <a className="text-blue-800 hover:text-blue-900">
                          <IdentificationIcon className="w-8 h-8 mr-2" />
                        </a>
                      </Link>

                      <Link href="#">
                        <a
                          onClick={deleteUser(user._id)}
                          className="text-blue-800 hover:text-blue-900">
                          <TrashIcon className="w-8 h-8" />
                        </a>
                      </Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          <nav
            className="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200"
            aria-label="Pagination">
            <div>
              <p className="text-sm text-gray-700">
                Showing <span className="font-medium">1</span> to{' '}
                <span className="font-medium">10</span> of <span className="font-medium">20</span>{' '}
                results
              </p>
            </div>

            <div className="hidden lg:block">
              <p className="text-sm font-medium">Total users: {users.length}</p>
            </div>

            <div className="flex">
              <a
                href="#"
                className="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                Previous
              </a>

              <a
                href="#"
                className="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                Next
              </a>
            </div>
          </nav>
        </div>
      </div>
    </>
  );
};

export default listUsers;

and the following api request in a file called delete.js /api/auth/delete.js

const { connectToDatabase } = require('@/lib/mongodb');
import User from '../../../models/user';

async function handler(req, res) {
  const data = req.body;
  const { id } = data;

  await connectToDatabase();

  const user = await User.findOne({ _id: id });

  if (!user) {
    throw new Error('User does not exist');
  }

  await User.deleteOne({ _id: id });

  res.status(200).json({ status: 'success' });
}

export default handler;

From what I can tell the api request is OK, and I can see the ID via the console.log, however, I get the following output when clicking the bin icon to delete the user

An unexpected error happened occurred: Error: Error: HTTP DELETE is not supported for /api/auth/delete/%20+%2061d6423c3ad20e077e290e64

This is the first time attempting something like this with react/nextjs.

Any help would be great.



Source: https://stackoverflow.com/questions/70601507/error-http-delete-is-not-supported-when-trying-to-delete-a-user-nextjs

Simple and customizable React UI components

Reliance Jio Brings Back Rs 499 Plan with OTT Benefit, 2GB Daily Data