Update Session Data in Database
#
Method 1) After session verification- NodeJS
- GoLang
- Python
- Other Frameworks
Important
For other backend frameworks, you can follow our guide on how to spin up a separate server configured with the SuperTokens backend SDK to authenticate requests and issue session tokens.
- Express
- Hapi
- Fastify
- Koa
- Loopback
- AWS Lambda / Netlify
- Next.js (Pages Dir)
- Next.js (App Dir)
- 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!.getSessionDataFromDatabase();
await session!.updateSessionDataInDatabase(
{ 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!.getSessionDataFromDatabase();
await session!.updateSessionDataInDatabase(
{ 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!.getSessionDataFromDatabase();
await session!.updateSessionDataInDatabase(
{ 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!.getSessionDataFromDatabase();
await session!.updateSessionDataInDatabase(
{ 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!.getSessionDataFromDatabase();
await session!.updateSessionDataInDatabase(
{ 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!.getSessionDataFromDatabase();
await session!.updateSessionDataInDatabase(
{ 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!.getSessionDataFromDatabase();
await session!.updateSessionDataInDatabase(
{ newKey: "newValue", ...currSessionData }
);
res.json({ message: "successfully updated session data in database" })
}
import { NextResponse, NextRequest } from "next/server";
import SuperTokens from "supertokens-node";
import { withSession } from "supertokens-node/nextjs";
import { backendConfig } from "@/app/config/backend";
SuperTokens.init(backendConfig());
export function POST(request: NextRequest) {
return withSession(request, async (err, session) => {
if (err) {
return NextResponse.json(err, { status: 500 });
}
let currSessionData = session!.getSessionDataFromDatabase();
await session!.updateSessionDataInDatabase(
{ newKey: "newValue", ...currSessionData }
);
return NextResponse.json({ message: "successfully updated session data in database" });
});
}
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(new AuthGuard())
async postExample(@Session() session: SessionContainer): Promise<{ message: string }> {
const currSessionData = session.getSessionDataFromDatabase();
// For more information about "AuthGuard" and the "Session" decorator please read our NestJS guide.
await session.updateSessionDataInDatabase(
{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.VerifySession
func updateInfo(w http.ResponseWriter, r *http.Request) {
// retrieve the session object as shown below
sessionContainer := session.GetSessionFromRequestContext(r.Context())
currSessionData, err := sessionContainer.GetSessionDataInDatabase()
if err != nil {
err = supertokens.ErrorHandler(err, r, w)
if err != nil {
// TODO: Send 500 to client
}
return
}
currSessionData["newKey"] = "newValue"
err = sessionContainer.UpdateSessionDataInDatabase(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_session
from supertokens_python.recipe.session import SessionContainer
from fastapi import Depends
from 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_from_database()
currSessionData['newKey'] = 'newValue'
await session.update_session_data_in_database(currSessionData)
return PlainTextResponse(content='success')
from supertokens_python.recipe.session.framework.flask import verify_session
from supertokens_python.recipe.session import SessionContainer
from 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.sync_get_session_data_from_database()
currSessionData['newKey'] = 'newValue'
session.sync_update_session_data_in_database(currSessionData)
return 'success'
from supertokens_python.recipe.session.framework.django.asyncio import verify_session
from django.http import HttpRequest
from 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_from_database()
currSessionData['newKey'] = 'newValue'
await session.update_session_data_in_database(currSessionData)
- We first require session verification in order to get the session object
- Using that object, we call the
updateSessionDataInDatabase
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
getSessionDataFromDatabase
for this session.
#
Method 2) Without session verification- NodeJS
- GoLang
- Python
- Other Frameworks
Important
For other backend frameworks, you can follow our guide on how to spin up a separate server configured with the SuperTokens backend SDK to authenticate requests and issue session tokens.
import Session from "supertokens-node/recipe/session";
async function updateSessionDataInDatabase() {
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 currSessionInfo = await Session.getSessionInformation(handle)
if (currSessionInfo === undefined) {
return;
}
let currSessionData = currSessionInfo.sessionDataInDatabase;
await Session.updateSessionDataInDatabase(handle,
{ newKey: "newValue", ...currSessionData }
);
})
}
import "github.com/supertokens/supertokens-golang/recipe/session"
func main() {
// we first get all the sessionHandles (string[]) for a user
tenantId := "public"
sessionHandles, err := session.GetAllSessionHandlesForUser("userId", &tenantId)
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
}
if sessionInfo == nil {
continue
}
currSessionData := sessionInfo.SessionDataInDatabase
currSessionData["newKey"] = "newValue"
_, err = session.UpdateSessionDataInDatabase(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_in_database, 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:
session_information = await get_session_information(handle)
if session_information is None:
continue
current_session_data = session_information.session_data_in_database
current_session_data["newKey"] = "newValue"
await update_session_data_in_database(handle, current_session_data)
from supertokens_python.recipe.session.syncio import get_all_session_handles_for_user, update_session_data_in_database, get_session_information
# we first get all the session_handles (List[string]) for a user
session_handles = get_all_session_handles_for_user("userId")
for handle in session_handles:
session_information = get_session_information(handle)
if session_information is None:
continue
current_session_data = session_information.session_data_in_database
current_session_data["newKey"] = "newValue"
update_session_data_in_database(handle, current_session_data)