Next.js Discord

Discord Forum

why showing invalid URL in clerk dashboard

Unanswered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
I am creating new endpoint in clerk for to make http request to create user data in User model through clerk webhook.

this is the url :
http://localhost:3000/api/webhooks/clerk

route path :
app/api/webhooks/clerk/route.ts

handler function in route.ts file:

import mongoose from "mongoose";
import UserModel from "@/lib/database/models/user.model";
import { NextApiRequest, NextApiResponse } from "next";

export default async function handler(req: NextApiRequest, res: NextApiResponse){
    if(req.method === 'POST'){
        try{
            console.log('Webhook data:',req.body)
        }catch(error){
            console.log('Error while processing clerk webhook:',error);
            res.status(500).send({
                message: 'Internal Server Error',
                error,
            })
        }
    }else {
        res.status(405).send({
            message: 'Method not allowed',
        })
    }
}

34 Replies

Northeast Congo LionOP
already I use in public route:
import { authMiddleware } from "@clerk/nextjs";
 
export default authMiddleware({
  publicRoutes: ['/', '/api/webhooks/clerk'],
});
 
export const config = {
  matcher: [    
    "/((?!.+\\.[\\w]+$|_next).*)",
    "/(api|trpc)(.*)"
  ]
};
Toyger
you can't use localhost as webhook, because localhost is pointing to local machine which for clerk will be their servers. you need to use ngrok for development https://ngrok.com/docs/integrations/clerk/webhooks/, to have some external url where webhook can be catched.
Northeast Congo LionOP
got new issue with api

import mongoose from "mongoose";
import UserModel from "@/lib/database/models/user.model";
import { NextApiRequest, NextApiResponse } from "next";

export async function handler(req: NextApiRequest, res: NextApiResponse){
    if(req.method === 'POST'){
        try{
            console.log('Webhook data:',req.body)
        }catch(error){
            console.log('Error while processing clerk webhook:',error);
            res.status(500).send({
                message: 'Internal Server Error',
                error,
            })
        }
    }else {
        res.status(405).send({
            message: 'Method not allowed',
        })
    }
}


unable to get console.log message
@Toyger in vercel console log works strange, you can look at github issues there is a lot issues/discussions about that. it can show with delay.
Northeast Congo LionOP
I am just trying see is it wokring or not without action creators, can I use api
?
so for that I console.log
but in server console.log not showing
Toyger
are you trying it locally or on vercel?
@Toyger are you trying it locally or on vercel?
Northeast Congo LionOP
locally
@Northeast Congo Lion locally
Toyger
you can check logs on clerk side, also show request info inside ngrok, in above url that I sent you can read more info about how to do it
@Toyger you can check logs on clerk side, also show request info inside ngrok, in above url that I sent you can read more info about how to do it
Northeast Congo LionOP
but its not showing console messages in logs of clerk
@Toyger you can check logs on clerk side, also show request info inside ngrok, in above url that I sent you can read more info about how to do it
Northeast Congo LionOP
bro, got error 405, is it something wrong. in it

export async function handler(req: NextApiRequest, res: NextApiResponse){
    if(req.method === 'POST'){
        try{
            console.log('Webhook data:',req.body)
        }catch(error){
            console.log('Error while processing clerk webhook:',error);
            res.status(500).send({
                message: 'Internal Server Error',
                error,
            })
        }
    }else {
        res.status(405).send({
            message: 'Method not allowed',
        })
    }
}


I am trying to make post request,
error : 405
I ain't using action creators
@Toyger what it shows about query?
Northeast Congo LionOP
POST status 405
Toyger
try to send POST to it with postman or insomnia
Northeast Congo LionOP
@Toyger
I created this in app > api > webhooks > clerk > route.ts

route.ts file
export async function POST(req: Request){
    const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET;

    if(!WEBHOOK_SECRET){
        throw new Error("Add WEBHOOK from Clerk dashboard");
    }

    // get headers
    const headerPayload = headers();
    const svix_id = headerPayload.get('svix-id');
    const svix_timestamp = headerPayload.get('svix-timestamp');
    const svix_signature = headerPayload.get('svix-signature');

    if(!svix_id || !svix_timestamp || !svix_signature){
        return new Response('Error Occured -- no svix headers', {
            status: 400,
        })
    }

    const payload = await req.json();
    const body = JSON.stringify(payload);

    // create svix instance with secret key
    const wh = new Webhook(WEBHOOK_SECRET);

    let evt: WebhookEvent;

    // verify payload with the headers
    try{
        evt = wh.verify(body, {
            'svix-id': svix_id,
            'svix-timestamp': svix_timestamp,
            'svix-signature': svix_signature,
        }) as WebhookEvent;
    }catch(error){
        console.log('Error while verifying webhook', error);
        return new Response('Error Occured:', {
            status: 400,
        })
    }
     
    const {id} = evt.data;
    const eventType = evt.type;

    if(eventType === 'user.created'){
        const {id, email_addresses, image_url, first_name, last_name, username} = evt.data;

        const user = {
            clerkId: id,
            email: email_addresses[0].email_address,
            username: username!,
            firstName: first_name,
            lastName: last_name,
            photo: image_url,
        };

        const newUser = await UserModel.create(user);

        return JSON.parse(JSON.stringify(newUser));
    }
}
but not created action creators, is this work
Northeast Congo LionOP
forget his
this
I created new one
app > api > webhooks > route.ts
import mongoose from "mongoose";
import { NextApiRequest, NextApiResponse } from "next";

import { WebhookEvent } from "@clerk/nextjs/server";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { clerkClient } from "@clerk/nextjs";
import {Webhook} from 'svix'
import { createUser } from "@/lib/actions/user.action";

export async function POST(req: Request){
    const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET;

    if(!WEBHOOK_SECRET){
        throw new Error("Add WEBHOOK from Clerk dashboard");
    }

    // get headers
    const headerPayload = headers();
    const svix_id = headerPayload.get('svix-id');
    const svix_timestamp = headerPayload.get('svix-timestamp');
    const svix_signature = headerPayload.get('svix-signature');

    if(!svix_id || !svix_timestamp || !svix_signature){
        return new Response('Error Occured -- no svix headers', {
            status: 400,
        })
    }

    const payload = await req.json();
    const body = JSON.stringify(payload);

    // create svix instance with secret key
    const wh = new Webhook(WEBHOOK_SECRET);

    let evt: WebhookEvent;

    // verify payload with the headers
    try{
        evt = wh.verify(body, {
            'svix-id': svix_id,
            'svix-timestamp': svix_timestamp,
            'svix-signature': svix_signature,
        }) as WebhookEvent;
    }catch(error){
        console.log('Error while verifying webhook', error);
        return new Response('Error Occured:', {
            status: 400,
        })
    }
     
    const { id } = evt.data;
    const eventType = evt.type;
    if(eventType === 'user.created'){
        const {id, email_addresses, image_url, first_name, last_name, username} = evt.data;

        const user = {
            clerkId: id,
            email: email_addresses[0].email_address,
            username: username!,
            firstName: first_name,
            lastName: last_name,
            photo: image_url,
        };

        const newUser = await createUser(user);

        return JSON.parse(JSON.stringify(newUser));

        if(newUser){
            await clerkClient.users.updateUserMetadata(id, {
                publicMetadata: {
                    userId: newUser._id,
                }
            })
        }
        return NextResponse.json({message: 'OK', user: newUser});
    }
}
still unable to store in database
@Knopper gall can you help me
user.action.ts file
"use server"

import connectDB from "../database/mongoose"
import userModel from "../database/models/user.model";
import { handleError } from "../utils";

export async function createUser(user: CreateUserParams){
    try{
        await connectDB();

        const newUser = await userModel.create(user);

        return JSON.parse(JSON.stringify(newUser));
    }catch(error){
        handleError(error);
    }
}
Knopper gall
Why did I get pinged o.0