Contents
    How to Display Steam Now Playing With Next.js

    How to Display Steam Now Playing With Next.js

    -- views

    Using Steam web API to display now playing steam on websites

    Introduction

    Who doesn't know steam? The most popular digital distribution platform for PC gaming with huge discounts during the steam summer sale or steam winter sale 🤣🤣🤣

    Steam now playing - Meme about Steam

    Despite its large user base, several people are unaware that Steam also offers a free application programming interface (API) called Steam Web API, which allows you to access the data of your games and playtime.

    Steam Web API is used on my website to display information about my gaming activities, such as online status, currently playing games, playing hours, etc.

    Steam now playing - Demo

    In this post, I'll explain how to use Next.js to display now playing steam on your website.

    What Is Steam API

    Steam Web API is an HTTP based web that can be used to access many Steam features for display on websites. The API is accessed using an HTTP request with the output of three different formats: JSON, XML, and VDF.

    What Does Steam API Do

    The Steam web API can do a variety of things, including get user information, get currently played, and many more, as shown below.

    • Get news for app: return the most recent version of a game provided by its appID.
    • Get Global Achievement Percentages For App: Returns on global achievements for a certain game, expressed as a percentage.
    • Get Player Summaries: returns basic profile information.
    • Get Friend List: Returns any Steam user's friend list if their Steam Community profile visibility is set to "Public."
    • Get Player Achievements: Returns a list of this user's achievements sorted by app id.
    • Get Owned Games: returns a list of games a player has, as well as information on how much time they've spent playing them.
    • Get Recently Played Games: returns a list of games played in the last two weeks by a player.

    Steam API Token

    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
    

    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.

    Steam now playing - Steam API key

    To get a 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.

    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.

    Creating an API Route

    Create a steam 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,
        },
      });
    }
    

    Add .env.local file with key and id that we get before (change the data below with yours and don't forget to restart the server).

    STEAM_TOKEN=ED20ADF0123188DHDHDHJASSFB
    STEAM_ID=76561198324704779
    

    Try accessing localhost:3000/api/playersummaries from the browser to get response like this.

    {
      "steam": {
        "getPersonName": "imyour_universe",
        "getAvatar": "https://avatars.akamai.steamstatic.com/759b364331bd3566df2ee48fd389fc0310789288_full.jpg",
        "getStatus": "Online",
        "getGames": false,
        "getprofileUrl": "https://steamcommunity.com/profiles/76561198324704779/"
      }
    }
    

    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

    yarn add swr
    
    # or
    
    npm i swr
    

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

    import useSWR from 'swr';
    
    const Games = () => {
      const fetcher = (url: RequestInfo) => fetch(url).then((res) => res.json());
      const { data } = useSWR('/api/playersummaries', fetcher);
    
      return <></>;
    };
    
    export default Games;
    

    Styling 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.

    import React from 'react';
    import useSWR from 'swr';
    
    const Games = () => {
      const fetcher = (url: RequestInfo) => fetch(url).then((res) => res.json());
      const { data } = useSWR('/api/playersummaries', fetcher);
    
      return (
        <>
          <main className='prose prose-invert max-w-none prose-a:no-underline'>
            <div className='mx-auto  mb-16 max-w-3xl text-center'>
              <h1 className='-my-1 text-3xl sm:text-5xl'>Steam Player Summaries</h1>
              <p className='text-md text-gray-400 sm:text-lg'>
                for now {data?.steam.getPersonName} is{' '}
                <span className='text-primary'>
                  {data?.steam.getGames === false
                    ? data?.steam.getStatus
                      ? data?.steam.getStatus
                      : '-'
                    : data?.steam.getGames}
                </span>
              </p>
            </div>
          </main>
        </>
      );
    };
    
    export default Games;
    

    Resources


    Post Reactions
    LIKE
    LOVE
    Wow
    YAY
    Contributors

    The writing on this website may contain errors in grammar, punctuation, etc. Please make a contribution here