Search code examples
javascriptnode.jsfetch-apix-www-form-urlencoded

Reddit API - Requesting Access Token using JavaScript


I am having trouble with the POST request format for retrieving the access token with the Reddit API. I am following the instructions for OAuth2 and was able to parse the URL for the initial 'code' after the user grants permission but I don't know what to include in the post request exactly. This is what I have so far, where returnCode is the code parsed from the URL, but I get a 401 response.

async function fetchToken(returnCode) {

    const form = new FormData();
    form.set('grant_type', 'authorization_code');
    form.set('code', returnCode);
    form.set('redirect_uri', 'http://localhost:3000/')

    const response = await fetch('https://www.reddit.com/api/v1/access_token', {
      method: 'POST',
      mode: 'no-cors',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        authorization: `Basic clientID + clientSecret`
      },
      body: form
    }).then(r => r.json())
    console.log(response);
  }

Any help would be appreciated.


Solution

  • You're passing a FormData request body which will have a content-type of multipart/form-data, not the required application/x-www-form-urlencoded. Try using URLSearchParams instead...

    const form = new URLSearchParams({
      grant_type: "authorization_code",
      code: returnCode,
      redirect_uri: "http://localhost:3000/"
    })
    

    Your authorization header is also incorrect. HTTP Basic authentication requires you to base64 encode the username and password

    const credentials = Buffer.from(`${clientID}:${clientSecret}`).toString("base64")
    
    const res = await fetch('https://www.reddit.com/api/v1/access_token', { 
      method: "POST",
      headers: {
        Authorization: `Basic ${credentials}`
      },
      body: form
    })
    if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`)
    return res.json()