Search code examples
node.jsoauth-2.0oauthnotion-api

Notion API OAuth Not working `invalid client`


I've tried setting up Notion OAuth and everything works fine on postman but on my application it's not.

I've tried many ways and this is the last implementation I've did so far.

router
.get("/notion/authorize", async (req : Request, res: Response) => { 
    let redirectURL = `${process.env.NOTION_AUTH_URL}?owner=user&client_id=${process.env.NOTION_CLIENT_ID}&response_type=code&redirect_uri=${encodeURI(process.env.NOTION_REDIRECT_URI)}`
    res.redirect(redirectURL)
})
.get("/notion/callback", async (req: Request<any,any, any, {code : string } >, res: Response) => {
    try {
        const {code} = req.query;
        console.log(code)
        if(!code) {
            throw new Error("Code is required from notion")
        }
        const response = await axios.post('https://api.notion.com/v1/oauth/token', { 
            data:JSON.stringify({
                "grant_type":"authorization_code",
                "code":code,
                "redirect_uri": "http://localhost:9000/notion/callback"
            }),
            headers: {
            "Authorization": `Basic ${Buffer.from(`${process.env.NOTION_CLIENT_ID}:${process.env.NOTION_CLIENT_SECRET}`).toString('base64')}`,
            "Content-Type": "application/json",
            }
        
        })
        const  {access_token, bot_id, workspace_id, workspace_name} =response.data;
        
        //.. more code

    }catch(err) {
        if(axios.isAxiosError(err)) {
            console.log(err.response.data, err.response.status)
        }
        return res.status(400).json({message: `Failed to register user ${err}`})
    }

    
})

Stil I get this as error { error: 'invalid_client' } 401

Also yes, checked the keys and redirect URI as well.

Please help me with this :)


Solution

  • It seems like your header is wrong. Check if the field authorization gives the same value as the one you use in postman.

    Other thing is your post request. I think you're messing up something. Axios can take one single object when using the request method or 3 parameters (url, data, config) when using the post method (Axios Documentation). In your code, the data and the headers are together and should be apart in different objects.