Updating the JWT
caution
Using JWTs is optional and is only required if you want to integrate with another service that relies on JWTs or if you want to integrate with a backend framework that we do not support yet
#
Method 1) After session verification- NodeJS
- GoLang
- Python
- Express
- Hapi
- Fastify
- Koa
- Loopback
- AWS Lambda / Netlify
- Next.js
- NestJS
import express from "express";import { verifySession } from "supertokens-node/recipe/session/framework/express";
let app = express();
app.post("/updateinfo", verifySession(), async (req, res) => {
let session = req.session;
let currAccessTokenPayload = session.getAccessTokenPayload();
await session.updateAccessTokenPayload( { newKey: "newValue", ...currAccessTokenPayload } );
res.json({ message: "successfully updated access token payload" })});
import Hapi from "@hapi/hapi";import { verifySession } from "supertokens-node/recipe/session/framework/hapi";import { SessionRequest } from "supertokens-node/framework/hapi";
let server = Hapi.server({ port: 8000 });
server.route({ path: "/updateinfo", method: "post", options: { pre: [ { method: verifySession() }, ], }, handler: async (req: SessionRequest, res) => { let session = req.session;
let currAccessTokenPayload = session!.getAccessTokenPayload();
await session!.updateAccessTokenPayload( { newKey: "newValue", ...currAccessTokenPayload } ); return res.response({ message: "successfully updated access token payload" }).code(200); }})
import Fastify from "fastify";import { verifySession } from "supertokens-node/recipe/session/framework/fastify";
let fastify = Fastify();
fastify.post("/updateinfo", { preHandler: verifySession(),}, async (req, res) => { let session = req.session;
let currAccessTokenPayload = session.getAccessTokenPayload();
await session.updateAccessTokenPayload( { newKey: "newValue", ...currAccessTokenPayload } ); res.send({ message: "successfully updated access token payload" });});
import { verifySession } from "supertokens-node/recipe/session/framework/awsLambda";import { SessionEvent } from "supertokens-node/framework/awsLambda";
async function updateinfo(awsEvent: SessionEvent) { let session = awsEvent.session;
let currAccessTokenPayload = session!.getAccessTokenPayload();
await session!.updateAccessTokenPayload( { newKey: "newValue", ...currAccessTokenPayload } );
return { body: JSON.stringify({ message: "successfully updated access token payload" }), statusCode: 200, };};
exports.handler = verifySession(updateinfo);
import KoaRouter from "koa-router";import { verifySession } from "supertokens-node/recipe/session/framework/koa";import { SessionContext } from "supertokens-node/framework/koa";
let router = new KoaRouter();
router.post("/updateinfo", verifySession(), async (ctx: SessionContext, next) => { let session = ctx.session;
let currAccessTokenPayload = session!.getAccessTokenPayload();
await session!.updateAccessTokenPayload( { newKey: "newValue", ...currAccessTokenPayload } ); ctx.body = { message: "successfully updated access token payload" };});
import { inject, intercept } from "@loopback/core";import { RestBindings, post, response } from "@loopback/rest";import { verifySession } from "supertokens-node/recipe/session/framework/loopback";import { SessionContext } from "supertokens-node/framework/loopback";
class UpdateInfo { constructor(@inject(RestBindings.Http.CONTEXT) private ctx: SessionContext) { } @post("/updateinfo") @intercept(verifySession()) @response(200) async handler() { let session = this.ctx.session;
let currAccessTokenPayload = session!.getAccessTokenPayload();
await session!.updateAccessTokenPayload( { newKey: "newValue", ...currAccessTokenPayload } ); return { message: "successfully updated access token payload" }; }}
import { superTokensNextWrapper } from 'supertokens-node/nextjs'import { verifySession } from "supertokens-node/recipe/session/framework/express";import { SessionRequest } from "supertokens-node/framework/express";
export default async function updateInfo(req: any, res: any) { await superTokensNextWrapper( async (next) => { await verifySession()(req, res, next); }, req, res ) let session = (req as SessionRequest).session;
let currAccessTokenPayload = session!.getAccessTokenPayload();
await session!.updateAccessTokenPayload( { newKey: "newValue", ...currAccessTokenPayload } ); res.json({ message: "successfully updated access token payload" })}
import { Controller, Post, UseGuards, Session } from "@nestjs/common";import { SessionContainer } from "supertokens-node/recipe/session";import { AuthGuard } from './auth/auth.guard';
@Controller()export class ExampleController { @Post('example') @UseGuards(AuthGuard) async postExample(@Session() session: SessionContainer): Promise<{ message: string }> { const currAccessTokenPayload = session.getAccessTokenPayload();
// For more information about "AuthGuard" and the "Session" decorator please read our NestJS guide. await session.updateAccessTokenPayload( {newKey: "newValue", ...currAccessTokenPayload} ); return { message: "successfully updated access token payload" }; }}
import ( "net/http"
"github.com/supertokens/supertokens-golang/recipe/session" "github.com/supertokens/supertokens-golang/supertokens")
// We assume that you have wrapped this handler with session.VerifySessionfunc updateInfo(w http.ResponseWriter, r *http.Request) { // retrieve the session object as shown below sessionContainer := session.GetSessionFromRequestContext(r.Context())
currAccessTokenPayload := sessionContainer.GetAccessTokenPayload()
currAccessTokenPayload["newKey"] = "newValue"
err := sessionContainer.UpdateAccessTokenPayload(currAccessTokenPayload) if err != nil { err = supertokens.ErrorHandler(err, r, w) if err != nil { // TODO: Send 500 to client } return }}
- FastAPI
- Flask
- Django
from supertokens_python.recipe.session.framework.fastapi import verify_sessionfrom fastapi import Dependsfrom fastapi.responses import PlainTextResponsefrom supertokens_python.recipe.session import SessionContainer
@app.post('/update_info') async def update_info(session: SessionContainer = Depends(verify_session())): # retrieve the session object as shown below current_access_token_payload = session.get_access_token_payload()
current_access_token_payload['newKey'] = 'newValue'
await session.update_access_token_payload(current_access_token_payload)
return PlainTextResponse(content='success')
from supertokens_python.recipe.session.framework.flask import verify_sessionfrom supertokens_python.recipe.session import SessionContainerfrom flask import g
@app.route('/update-jwt', methods=['POST']) @verify_session()def update_info(): session: SessionContainer = g.supertokens
# retrieve the session object as shown below current_access_token_payload = session.get_access_token_payload()
current_access_token_payload['newKey'] = 'newValue'
session.sync_update_access_token_payload(current_access_token_payload)
return 'success'
from supertokens_python.recipe.session.framework.django.asyncio import verify_sessionfrom django.http import HttpRequestfrom supertokens_python.recipe.session import SessionContainer
@verify_session()async def update_info(request: HttpRequest): session: SessionContainer = request.supertokens # retrieve the session object as shown below current_access_token_payload = session.get_access_token_payload()
current_access_token_payload['newKey'] = 'newValue'
await session.update_access_token_payload(current_access_token_payload)
- We first require session verification in order to get the session object
- Using that object, we call the
updateAccessTokenPayload
with new content. This content completely overrides the existing object, that's why we first get thecurrAccessTokenPayload
info. - The result is that the access token is updated in the user's browser cookies. The change is instantly visible on the frontend and the subsequent backend API calls.
#
Method 2) Without session verificationcaution
Changes to the access token payload via this method are reflected in the session only once the session is refreshed. So use method (1) whenever possible.
- NodeJS
- GoLang
- Python
import Session from "supertokens-node/recipe/session";
async function updateJWT() { let userId = "..."; // we first get all the sessionHandles (string[]) for a user let sessionHandles = await Session.getAllSessionHandlesForUser(userId);
// we update all the session's Access Token payloads for this user sessionHandles.forEach(async (handle) => { let currAccessTokenPayload = (await Session.getSessionInformation(handle)).accessTokenPayload;
await Session.updateAccessTokenPayload(handle, { newKey: "newValue", ...currAccessTokenPayload } ); })}
import "github.com/supertokens/supertokens-golang/recipe/session"
func main() { // we first get all the sessionHandles (string[]) for a user sessionHandles, err := session.GetAllSessionHandlesForUser("userId") if err != nil { // TODO: handle error return }
// we update all the session's access token payloads for this user for _, handle := range sessionHandles { sessionInfo, err := session.GetSessionInformation(handle) if err != nil { // TODO: handle error return }
currAccessTokenPayload := sessionInfo.AccessTokenPayload currAccessTokenPayload["newKey"] = "newValue"
err = session.UpdateAccessTokenPayload(handle, currAccessTokenPayload) if err != nil { // TODO: handle error return } }}
- Asyncio
- Syncio
from supertokens_python.recipe.session.asyncio import get_all_session_handles_for_user, update_access_token_payload, get_session_information
async def some_func(): # we first get all the session_handles (List[string]) for a user session_handles = await get_all_session_handles_for_user("userId")
for handle in session_handles: current_jwt_payload = await get_session_information(handle)
current_access_token_payload = current_jwt_payload.access_token_payload current_access_token_payload["newKey"] = "newValue" await update_access_token_payload(handle, current_access_token_payload)
from supertokens_python.recipe.session.syncio import get_all_session_handles_for_user, update_access_token_payload, get_session_information
# we first get all the session_handles (List[string]) for a usersession_handles = get_all_session_handles_for_user("userId")
for handle in session_handles: session_information = get_session_information(handle)
current_access_token_payload = session_information.access_token_payload current_access_token_payload["newKey"] = "newValue" update_access_token_payload(handle, current_access_token_payload)