Search code examples
javascriptreactjsapireddit

Reddit API /api/me unable to make it work


I managed to get Reddit OAuth to work and it is getting redirected to my homepage. And I am getting a URL like http://localhost:3000/?state=XEA12&code=6p4pAyle2EWGVwIBlFJ6ERXjxKg

Now, when I try other APIs like /api/me. I am not able to get it working. I have also set the scope of my app to identity.

Here is the code snippet that I wrote:

import axios from "axios";
import useSWR from "swr";

const link = "https://www.reddit.com/api/v1/me";

const config = {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    Authorization: "bearer 6p4pAyle2EWGVwIBlFJ6ERXjxKg",
  },
};

const fetcher = (url) => axios.get(url, config).then((res) => res);

export default function Home() {
  const { data, error } = useSWR(link, fetcher);
  if (error) return <div>failed to load </div>;
  if (!data) return <div>loading...</div>;
  return <div>{JSON.stringify(data)}</div>;
}

Can you please tell me what I am doing wrong? Is it because of the headers or do I need to pass something else?


Solution

  • According to the documentation you need to retrieve access_token first, by using code param. Here is how to do that: https://github.com/reddit-archive/reddit/wiki/OAuth2#retrieving-the-access-token

    Then you can use that access_token in a bearer auth. There is another note: API requests with a bearer token should be made to https://oauth.reddit.com, NOT www.reddit.com. Hope it will help