# Is there support for refresh tokens in Nakama-js?

**URL:** <https://forum.heroiclabs.com/t/is-there-support-for-refresh-tokens-in-nakama-js/1689>\
**Category:** Game Design\
**Tags:** authentication, sdk-javascript\
**Created:** [June 5, 2021, 11:28pm UTC](https://forum.heroiclabs.com/t/is-there-support-for-refresh-tokens-in-nakama-js/1689 "2021-06-05T23:28:16Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![hybridlink](https://avatars.discourse-cdn.com/v4/letter/h/ce73a5/32.png) [@hybridlink](https://forum.heroiclabs.com/u/hybridlink)\
**Post date:** [June 5, 2021, 11:28pm UTC](https://forum.heroiclabs.com/t/is-there-support-for-refresh-tokens-in-nakama-js/1689/1 "2021-06-05T23:28:16Z")

</div>

Hi, Have some problems with using nakama js client, what should I’d when the token will expired soon? client.authenticateEmail return session didn’t bring refresh\_token like account/authenticate/device api, if it will return refresh\_token how could I use refresh\_token to get a renew token?

```auto
const client = new Client("defaultkey", "127.0.0.1", "7350");
const session = await client.authenticateEmail(email, password, false, name);

```

Nakama Server : 3.3.0  
nakama-js : 2.1.5

Thanks for helping!

---

<div class="post-metadata">

**Author:** ![gamedev-js](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/gamedev-js/32/670_2.png) [@gamedev-js](https://forum.heroiclabs.com/u/gamedev-js)\
**Post date:** [June 7, 2021, 1:37am UTC](https://forum.heroiclabs.com/t/is-there-support-for-refresh-tokens-in-nakama-js/1689/2 "2021-06-07T01:37:46Z")

</div>

You can use this method.

```auto
async checkSessionAndAuthenticate() => { 
        let nakamaAuthToken = localStorage.getItem("nakamaAuthToken");
        if (nakamaAuthToken && nakamaAuthToken != "") {
            this.logger.log("Session Found");

            this.session = Session.restore(nakamaAuthToken);
            let currentTimeInSec = new Date() / 1000;
    
            if (!this.session.isexpired(currentTimeInSec)) {
                // Session valid so restore it
                this.session = this.session;
                this.logger.log("Session Restored");
                
            } else {
                this.logger.warn("Session Expired");
                
                await this.createSession()
            }
        } else {
            await this.createSession()
        }

        if(this.uselogs) {
            this.logger.success("Authenticated Session");
        }
    }checkSessionAndAuthenticate = async () => { 
        let nakamaAuthToken = localStorage.getItem("nakamaAuthToken");
        if (nakamaAuthToken && nakamaAuthToken != "") {
            this.logger.log("Session Found");

            this.session = Session.restore(nakamaAuthToken);
            let currentTimeInSec = new Date() / 1000;
    
            if (!this.session.isexpired(currentTimeInSec)) {
                // Session valid so restore it
                this.session = this.session;
                this.logger.log("Session Restored");
                
            } else {
                this.logger.warn("Session Expired");
                
                await this.createSession()
            }
        } else {
            await this.createSession()
        }

        if(this.uselogs) {
            this.logger.success("Authenticated Session");
        }
    }

```

---

<div class="post-metadata">

**Author:** ![hybridlink](https://avatars.discourse-cdn.com/v4/letter/h/ce73a5/32.png) [@hybridlink](https://forum.heroiclabs.com/u/hybridlink)\
**Post date:** [June 7, 2021, 2:05am UTC](https://forum.heroiclabs.com/t/is-there-support-for-refresh-tokens-in-nakama-js/1689/3 "2021-06-07T02:05:37Z")

</div>

Hi gamedev-js  
Thanks for your graceful reply, could I have more information about which api is createSession() use?

---

<div class="post-metadata">

**Author:** ![gamedev-js](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/gamedev-js/32/670_2.png) [@gamedev-js](https://forum.heroiclabs.com/u/gamedev-js)\
**Post date:** [June 7, 2021, 2:10pm UTC](https://forum.heroiclabs.com/t/is-there-support-for-refresh-tokens-in-nakama-js/1689/4 "2021-06-07T14:10:50Z")

</div>

you can get more info in this repo, is a wrapper for Playcanvas but the code is the same for any engine: [GitHub - zentyk/pc.nakama: A wrapper for heroiclabs/nakama JS client for use in playcanvas.](https://github.com/zentyk/pc.nakama)

```auto
import {Client, Session} from "@heroiclabs/nakama-js"
import Logger from "./logger"

export default class Nakama {
    constructor(clientHost,clientPort,useSSL, userId, username, uselogs) {
        this.loaded = false;
        
        this.userId = userId;
        this.username = username;
        this.useSSL=useSSL;

        this.socket;
        this.session;
        this.socketsession;
        this.match;
        this.oponents = [];

        this.logger = new Logger(uselogs);
        this.client = new Client("defaultkey", clientHost, clientPort, useSSL);
    }

    initiate = async ()=> {
        await this.checkSessionAndAuthenticate()
        await this.establishSocketConnection()

        this.loaded=true;
        this.logger.log("pc.nakama has loaded! and logged In!", "✨");
    }

    checkSessionAndAuthenticate = async () => { 
        let nakamaAuthToken = localStorage.getItem("nakamaAuthToken");
        if (nakamaAuthToken && nakamaAuthToken != "") {
            this.logger.log("Session Found");

            this.session = Session.restore(nakamaAuthToken);
            let currentTimeInSec = new Date() / 1000;
    
            if (!this.session.isexpired(currentTimeInSec)) {
                // Session valid so restore it
                this.session = this.session;
                this.logger.log("Session Restored");
                
            } else {
                this.logger.warn("Session Expired");
                
                await this.createSession()
            }
        } else {
            await this.createSession()
        }

        if(this.uselogs) {
            this.logger.success("Authenticated Session");
        }
    }

    establishSocketConnection = async () => {
        // Create connection to the server via websockets
        const trace = false; // TODO: understand what this does
        this.socket = this.client.createSocket(this.useSSL, trace);
        await this.socket.connect(this.session);
        
        this.logger.success("Established Websocket Connection");
    };

    createSession = async () => {
        this.logger.log("Creating New Session...");
        let nakamaSession = await this.client.authenticateCustom(this.userId, true, this.username);
        localStorage.setItem("nakamaAuthToken", nakamaSession.token);
        this.session = nakamaSession;   
        return this.session
    }

    createMatch = async () => {
        this.match = await this.socket.createMatch();
        this.logger.success("Created match with ID: " + this.match.match_id);
        return this.match;
    }

    joinToMatch = async (id) => {
        this.match = await this.socket.joinMatch(id);

        this.oponents = this.match.presences.filter((presence) => {
            // Remove your own user from list.
            return presence.user_id != this.match.self.user_id;
        });

        this.oponents.forEach((opponent) => {
            this.logger.log("User id %o, username %o.", opponent.user_id, opponent.username);
        });
    }

    matchMake = async (matchId, token) => {
        this.match = await this.socket.joinMatch(matchId,token);
    }

    rpcFindMatch = async () => {

    }
}

```

---

<div class="post-metadata">

**Author:** ![lugehorsam](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/lugehorsam/32/314_2.png) [@lugehorsam](https://forum.heroiclabs.com/u/lugehorsam)\
**Post date:** [June 7, 2021, 5:53pm UTC](https://forum.heroiclabs.com/t/is-there-support-for-refresh-tokens-in-nakama-js/1689/5 "2021-06-07T17:53:37Z")

</div>

Hey @hybridlink we’ll be releasing support for refresh tokens for the js client soon.

---

<div class="post-metadata">

**Author:** ![hybridlink](https://avatars.discourse-cdn.com/v4/letter/h/ce73a5/32.png) [@hybridlink](https://forum.heroiclabs.com/u/hybridlink)\
**Post date:** [June 8, 2021, 2:52am UTC](https://forum.heroiclabs.com/t/is-there-support-for-refresh-tokens-in-nakama-js/1689/6 "2021-06-08T02:52:11Z")

</div>

Hi @lugehorsam I’ve been struggling for a while, thank you for helping!
