Update Session Data
#
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";import { SessionRequest } from "supertokens-node/framework/express";
let app = express();
app.post("/updateinfo", verifySession(), async (req: SessionRequest, res) => {
let session = req.session;
let currSessionData = session!.getSessionData();
await session!.updateSessionData( { newKey: "newValue", ...currSessionData } );
res.json({ message: "successfully updated Session data in the database" })});
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 currSessionData = session!.getSessionData();
await session!.updateSessionData( { newKey: "newValue", ...currSessionData } ); return res.response({ message: "successfully updated Session data in the database" }).code(200); }})
import Fastify from "fastify";import { verifySession } from "supertokens-node/recipe/session/framework/fastify";import { SessionRequest } from "supertokens-node/framework/fastify";
let fastify = Fastify();
fastify.post("/updateinfo", { preHandler: verifySession(),}, async (req: SessionRequest, res) => { let session = req.session;
let currSessionData = session!.getSessionData();
await session!.updateSessionData( { newKey: "newValue", ...currSessionData } ); res.send({ message: "successfully updated Session data in the database" });});
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 currSessionData = session!.getSessionData();
await session!.updateSessionData( { newKey: "newValue", ...currSessionData } );
return { body: JSON.stringify({ message: "successfully updated Session data in the database" }), 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 currSessionData = session!.getSessionData();
await session!.updateSessionData( { newKey: "newValue", ...currSessionData } ); ctx.body = { message: "successfully updated Session data in the database" };});
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 currSessionData = session!.getSessionData();
await session!.updateSessionData( { newKey: "newValue", ...currSessionData } ); return { message: "successfully updated Session data in the database" }; }}
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 currSessionData = session!.getSessionData();
await session!.updateSessionData( { newKey: "newValue", ...currSessionData } ); res.json({ message: "successfully updated access token payload" })}
import { Controller, Post, UseGuards, Request, Response, 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();
const currSessionData = session.getSessionData();
// For more information about "AuthGuard" and the "Session" decorator please read our NestJS guide. await session.updateSessionData( {newKey: "newValue", ...currSessionData} ); return {message: "successfully updated Session data in the database"}; }}
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())
currSessionData, err := sessionContainer.GetSessionData() if err != nil { err = supertokens.ErrorHandler(err, r, w) if err != nil { // TODO: Send 500 to client } return }
currSessionData["newKey"] = "newValue"
err = sessionContainer.UpdateSessionData(currSessionData) 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 supertokens_python.recipe.session import SessionContainerfrom fastapi import Dependsfrom fastapi.responses import PlainTextResponse
@app.post('/update_info') async def update_info(session: SessionContainer = Depends(verify_session())): # retrieve the session object as shown below currSessionData = await session.get_session_data()
currSessionData['newKey'] = 'newValue'
await session.update_session_data(currSessionData)
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 currSessionData = session.get_access_token_payload()
currSessionData['newKey'] = 'newValue'
session.sync_update_session_data(currSessionData)
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 currSessionData = await session.get_session_data()
currSessionData['newKey'] = 'newValue'
await session.update_session_data(currSessionData)
- We first require session verification in order to get the session object
- Using that object, we call the
updateSessionData
with new content. This content completely overrides the existing object, that's why we first get thecurrSessionData
info. - The result is that the session data stored in the database (against the verified session) is updated. The change is instantly visible to other calls of
getSessionData
for this session.
#
Method 2) Without session verification- NodeJS
- GoLang
- Python
import Session from "supertokens-node/recipe/session";
async function updateSessionData() { let userId = "..."; // we first get all the sessionHandles (string[]) for a user let sessionHandles = await Session.getAllSessionHandlesForUser(userId);
// we update all the session's data for this user sessionHandles.forEach(async (handle) => { let currSessionData = (await Session.getSessionInformation(handle)).sessionData;
await Session.updateSessionData(handle, { newKey: "newValue", ...currSessionData } ); })}
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 session data for this user for _, handle := range sessionHandles { sessionInfo, err := session.GetSessionInformation(handle) if err != nil { // TODO: handle error return }
currSessionData := sessionInfo.SessionData currSessionData["newKey"] = "newValue"
err = session.UpdateSessionData(handle, currSessionData) if err != nil { // TODO: handle error return } }}
- Asyncio
- Syncio
from supertokens_python.recipe.session.asyncio import get_all_session_handles_for_user, update_session_data, 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_session_payload = await get_session_information(handle) current_session_payload = current_session_payload.session_data
current_session_payload["newKey"] = "newValue" await update_session_data(handle, current_session_payload)
from supertokens_python.recipe.session.syncio import get_all_session_handles_for_user, update_session_data, 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: current_session_payload = get_session_information(handle) current_session_payload = current_session_payload.session_data
current_session_payload["newKey"] = "newValue" update_session_data(handle, current_session_payload)