How to Create Steam Player Summaries With Next.js

jagadyudha

Jagad Yudha Awali

Posted on February 7, 2022

How to Create Steam Player Summaries With Next.js

Introduction

Who doesn't know steam? The most popular digital distribution platform for PC gaming.

Despite its large user base, several people are unaware that Steam also offers a free application programming interface (API) called Steamworks, which allows developers to integrate many of Steam's features, including matchmaking, in-game achievements, microtransactions, and content support, into their products.

Steamworks, as previously mentioned, is used on my website to display information about my gaming activities, such as online status, currently playing games, playing hours, etc.

demo of team Player Summaries

You can check live demo on [my website (https://jagad.xyz/activities)


1. Dive into Steam Web API Documentation

The most basic thing to do is to read the documentation from Steam directly. It can be seen in the GetPlayerSummaries (v0002) section. Steam provides an example URL as follows :

https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=YOUR-STEAM-KEY&steamids=YOUR-STEAM-ID
Enter fullscreen mode Exit fullscreen mode

From that URL, we can replace the steam key and id with your own.

We can get the key by accessing this Web API Key for Steam - Steam Community.

get API key from steam

To get the steam id, we can use the most primitive method by logging in through the browser and going to the steam profile section. In the URL bar, we will see the steam id.

get steam id

Use a browser to access the URL that already contains the key and id, or use Postman if you want it to be easier to read.


2. Implementation with Next.js API

Create a API route in /pages/api/playersummaries.tsx

import type { NextApiRequest, NextApiResponse } from "next";

export const getPlayerSummaries = () => {
  const playersummaries_endpoint = `http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=${process.env.STEAM_TOKEN}&steamids=${process.env.STEAM_ID}`;
  return fetch(playersummaries_endpoint, {
    method: "GET",
  });
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const response = await getPlayerSummaries();

  if (response.status != 200) {
    return res.status(200).json({
      steam: {
        personastate: "Offline",
      },
    });
  }

  const steam = await response.json();
  if (steam.item === null) {
    return res.status(200).json({
      steam: {
        personastate: "Offline",
      },
    });
  }
  const getPersonName = steam.response.players[0].personaname;
  const getAvatar = steam.response.players[0].avatarfull;
  const getStatus =
    steam.response.players[0].personastate === 1
      ? "Online 😆"
      : steam.response.players[0].personastate === 2
      ? "Busy 😐"
      : steam.response.players[0].personastate === 3
      ? "Away 🥱"
      : "Offline 😴";

  const getGames = !steam.response.players[0].gameextrainfo
    ? false
    : `Playing - ${steam.response.players[0].gameextrainfo} 😆`;
  const getprofileUrl = steam.response.players[0].profileurl;
  return res.status(200).json({
    steam: {
      getPersonName,
      getAvatar,
      getStatus,
      getGames,
      getprofileUrl,
    },
  });
}
Enter fullscreen mode Exit fullscreen mode

Add .env.local with key and id that we get before (change the data below with yours)

STEAM_TOKEN=ED20ADF0123188DHDHDHJASSFB
STEAM_ID=76561198324704779
Enter fullscreen mode Exit fullscreen mode

Try accessing localhost:3000/api/playersummaries to get response like this :

Response API


3. Fetching API with SWR

To fetch data from next.js API, we can use SWR. SWR is a library that can stream data updates constantly and automatically. And the UI will always be fast and reactive.

Install SWR with yarn add swr or npm i swr

SWR can be placed in pages/index.tsx or wherever else you choose.

import useSWR from 'swr';

const Games = () => {
  const fetcher = (url: RequestInfo) => fetch(url).then((res) => res.json());
  const { data } = useSWR('/api/playersummaries', fetcher);

  return (
    <section className='mb-16 container'>
    </section>
  );
};

export default Games;
Enter fullscreen mode Exit fullscreen mode

4. Styled With Tailwind CSS

This code can be placed inside the section to render the data from SWR.

You can also modify the style to suit your preferences.

<section className="mb-16 container">
  <div className="rounded-lg items-center border border-white border-opacity-10">
    <div className="flex py-6 my-auto rounded-md">
      <div className="flex my-auto ml-5 mr-4">
        <div className="w-20 h-20 flex items-center justify-center rounded-lg">
          {data?.steam.getAvatar ? (
            <img
              className="rounded-lg"
              src={data?.steam.getAvatar}
              width={100}
              height={100}
              alt="steam profil picture"
            />
          ) : (
            <div></div>
          )}
        </div>
        <div className="my-auto ml-3">
          <p className="text-md sm:text-xl text-white">
            {data?.steam.getPersonName ? data?.steam.getPersonName : "~"}
            <div className="text-md sm:text-lg text-white font-semibold">
              {data?.steam.getGames === false ? (
                <p>{data?.steam.getStatus ? data?.steam.getStatus : "-"}</p>
              ) : (
                <p className="text-white font-normal">{data?.steam.getGames}</p>
              )}
            </div>
          </p>
        </div>
      </div>
    </div>
  </div>
</section>
Enter fullscreen mode Exit fullscreen mode

This article was originally published on jagad.xyz

💖 💪 🙅 🚩
jagadyudha
Jagad Yudha Awali

Posted on February 7, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related