Where should I put the API keys of discourse so that I can fetch the posts?

I’m trying to fetch the posts of my discourse but i don’t know where should I put my API keys. So I’m trying to do a fetch to a: https://{defaultHost}/posts/{id}.json but it is giving me error as I haven’t introduced the API keys, but where should I introduce the API keys?

I’m not sure how you are making your api requests (which tool or programming language), but the api key and username go in the http header.

Here is a curl example from the Discourse API Documentation

curl -X POST "http://127.0.0.1:3000/categories" \
-H "Content-Type: multipart/form-data;" \
-H "Api-Key: 714552c6148e1617aeab526d0606184b94a80ec048fc09894ff1a72b740c5f19" \
-H "Api-Username: discourse1" \
-F "name=89853c20-4409-e91a-a8ea-f6cdff96aaaa" \
-F "color=49d9e9" \
-F "text_color=f0fcfd"
2 Likes

I’m doing it in nextJS. Where should I put that code?

I’m not familiar with nextJS so I’m not totally sure, but looks like nextJS uses a tool called SWR to make api requests

You need to be VERY careful the scope of the API key you are storing client side and which api calls you make to Discourse so that you don’t expose your global API key to users since it looks like nextJS is a client side framework instead of server side. The proper way is probably to have next.js make a server side api request that then makes an authenticated api call out to your Discourse instance.

This answer might help you out:

As per the docs Arguments – SWR you should do

const fetcher = (url, token) =>
    axios
      .get(url, { headers: { Authorization: "Bearer " + token } })
      .then((res) => res.data);

const { data, error } = useSWR(
  [`http://localhost:8000/api/v1/users/get-avatar`, auth.token],
  fetcher
);
if (error) console.log(error);
if (data) console.log(data);
1 Like