Fetching Data from the Clash of Clans API Using getServerSideProps() in Next.js

Milind Dhamu
2 min readAug 18, 2023

--

The Clash of Clans API provides a wealth of data about player profiles and game information. In this tutorial, we’ll explore how to fetch player data from the Clash of Clans API using getServerSideProps in a Next.js application, ensuring that we always have the latest information when a user accesses the page.

Prerequisites

Before we get started, make sure you have the following:

  1. Clash of Clans API JWT Token: To access the Clash of Clans API, you’ll need a JSON Web Token (JWT) token. You can obtain one by registering your application on the Clash of Clans Developer Portal.
  2. Node.js and npm: Ensure you have Node.js and npm (Node Package Manager) installed on your machine.
  3. Basic Understanding of Next.js: We’ll be using Next.js to build our application. Familiarity with Next.js concepts such as pages and routing will be helpful.

Setting Up the Project

Let’s start by setting up a new Next.js project:

npx create-next-app clash-of-clans-app
cd clash-of-clans-app

Next, install Axios, which we’ll use to make API requests:

npm install axios

Fetching Data Using getServerSideProps()

In Next.js, the getServerSideProps function allows us to fetch data on the server side and pass it as props to our page components. Here's how we can use it to fetch player data from the Clash of Clans API:

// pages/playerTag.js

import axios from "axios";

const PlayerInfo = ({ playerData }) => {
if (!playerData) {
return <p>Error fetching player data.</p>;
}

return (
<div>
{/* Render player data here */}
</div>
);
};

export async function getServerSideProps() {
const playerTag = "#2LQUJU9YC"; // Use your own Tag
const apiUrl = `https://api.clashofclans.com/v1/players/${playerTag}`;
const token = "YOUR_JWT_TOKEN"; // Replace with your JWT token

try {
const response = await axios.get(apiUrl, {
headers: {
Authorization: `Bearer ${token}`
}
});

const playerData = response.data;

return {
props: {
playerData
}
};
} catch (error) {
console.error("Error fetching player data:", error);
return {
props: {}
};
}
}

export default PlayerInfo;

In this example, we use getServerSideProps to fetch the player data from the Clash of Clans API using Axios and a JWT token. The fetched data is then passed as props to the PlayerInfo component.

Conclusion

In this tutorial, we’ve learned how to fetch player data from the Clash of Clans API using getServerSideProps in a Next.js application. This approach ensures that we always have the latest information when users access the page, making our application more responsive and up-to-date.

Remember to replace "YOUR_JWT_TOKEN" with your actual JWT token obtained from the Clash of Clans API developer console. With this knowledge, you can now build dynamic and data-driven applications that utilize real-time data from external APIs.

Happy coding!

--

--