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?
AI-generated summary
Where to Put API Keys in Discourse for Fetching Posts
Allen_Chen is trying to fetch posts from Discourse using an API, but is unsure where to put the API keys. blake suggests that the API key and username go in the HTTP header, providing a curl example from the Discourse API documentation.
As Allen_Chen is using Next.js, blake warns of the importance of securing the API key when making client-side requests. To avoid exposing the global API key to users, blake recommends making server-side API requests from Next.js, which can then make authenticated API calls to Discourse. An example using useSWR and axios is provided to help with implementation.
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 REST 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"
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 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);