Session Verification using getSession
caution
Please use the verifySession middleware whenever possible as it is simpler to use.
#
Requiring an active session- NodeJS
- GoLang
- Python
- Express
- Hapi
- Fastify
- Koa
- Loopback
- AWS Lambda / Netlify
- Next.js
- NestJS
import express from "express";import Session from "supertokens-node/recipe/session";
let app = express();
app.post("/like-comment", async (req, res) => {
let session = await Session.getSession(req, res);
if (session === undefined) { throw Error("Should never come here") }
let userId = session.getUserId(); //....});
import Hapi from "@hapi/hapi";import Session from "supertokens-node/recipe/session";
let server = Hapi.server({ port: 8000 });
server.route({ path: "/like-comment", method: "post", handler: async (req, res) => { let session = await Session.getSession(req, res);
if (session === undefined) { throw Error("Should never come here") } let userId = session.getUserId(); //... }})
import Fastify from "fastify";import Session from "supertokens-node/recipe/session";
let fastify = Fastify();
fastify.post("/like-comment", async (req, res) => { let session = await Session.getSession(req, res);
if (session === undefined) { throw Error("Should never come here") } let userId = session.getUserId(); //....});
import Session from "supertokens-node/recipe/session";import { middleware } from "supertokens-node/framework/awsLambda";import { SessionEvent } from "supertokens-node/framework/awsLambda";
async function likeComment(awsEvent: SessionEvent) { let session = await Session.getSession(awsEvent, awsEvent);
if (session === undefined) { throw Error("Should never come here") } let userId = session.getUserId(); //....};
exports.handler = middleware(likeComment);
import KoaRouter from "koa-router";import Session from "supertokens-node/recipe/session";
let router = new KoaRouter();
router.post("/like-comment", async (ctx, next) => { let session = await Session.getSession(ctx, ctx);
if (session === undefined) { throw Error("Should never come here") } let userId = session.getUserId(); //....});
import { inject } from "@loopback/core";import { RestBindings, MiddlewareContext, post, response } from "@loopback/rest";import Session from "supertokens-node/recipe/session";
class LikeComment { constructor(@inject(RestBindings.Http.CONTEXT) private ctx: MiddlewareContext) { } @post("/like-comment") @response(200) async handler() { let session = await Session.getSession(this.ctx, this.ctx);
if (session === undefined) { throw Error("Should never come here") } let userId = session.getUserId(); //.... }}
import { superTokensNextWrapper } from 'supertokens-node/nextjs'import Session from "supertokens-node/recipe/session";import { SessionRequest } from "supertokens-node/framework/express";
export default async function likeComment(req: SessionRequest, res: any) { let session = await superTokensNextWrapper( async (next) => { return await Session.getSession(req, res); }, req, res )
if (session === undefined) { throw Error("Should never come here") } let userId = session.getUserId(); //....}
import { Controller, Post, UseGuards, Req, Res } from "@nestjs/common";import type { Request, Response } from "express";import { AuthGuard } from './auth/auth.guard';import Session from "supertokens-node/recipe/session";
@Controller()export class ExampleController { @Post('example') @UseGuards(AuthGuard) async postExample(@Req() req: Request, @Res({passthrough: true}) res: Response): Promise<boolean> { // This should be done inside a parameter decorator, for more information please read our NestJS guide. const session = await Session.getSession(req, res);
if (session === undefined) { throw Error("Should never come here") } const userId = session.getUserId(); //.... return true; }}
import ( "fmt" "net/http"
"github.com/supertokens/supertokens-golang/recipe/session" "github.com/supertokens/supertokens-golang/supertokens")
func likeCommentAPI(w http.ResponseWriter, r *http.Request) { sessionContainer, err := session.GetSession(r, w, nil)
if err != nil { err = supertokens.ErrorHandler(err, r, w) if err != nil { // TODO: send 500 to client } return }
userID := sessionContainer.GetUserID()
// TODO: API logic... fmt.Println(userID)}
- FastAPI
- Flask
- Django
from supertokens_python.recipe.session.asyncio import get_sessionfrom fastapi.requests import Request
@app.post('/like-comment') async def like_comment(request: Request): session = await get_session(request)
if session is None: raise Exception("Should never come here")
user_id = session.get_user_id()
print(user_id) # TODO
from supertokens_python.recipe.session.syncio import get_sessionfrom flask.wrappers import Request
@app.route('/like-comment', methods=['POST']) def like_comment(request: Request): session = get_session(request)
if session is None: raise Exception("Should never come here")
user_id = session.get_user_id()
print(user_id) # TODO
from supertokens_python.recipe.session.asyncio import get_sessionfrom django.http import HttpRequest
async def like_comment(request: HttpRequest): session = await get_session(request) if session is None: raise Exception("Should never come here")
user_id = session.get_user_id()
print(user_id) # TODO
#
Optional session verificationSometimes, you want an API to be accessible even if there is no session. In that case, you can use the sessionRequired
flag:
- NodeJS
- GoLang
- Python
- Express
- Hapi
- Fastify
- Koa
- Loopback
- AWS Lambda / Netlify
- Next.js
- NestJS
import express from "express";import Session from "supertokens-node/recipe/session";
let app = express();
app.post("/like-comment", async (req, res) => {
let session = await Session.getSession(req, res, { sessionRequired: false })
if (session !== undefined) { let userId = session.getUserId(); } else { // user is not logged in... } //....});
import Hapi from "@hapi/hapi";import Session from "supertokens-node/recipe/session";
let server = Hapi.server({ port: 8000 });
server.route({ path: "/like-comment", method: "post",
handler: async (req, res) => { let session = await Session.getSession(req, res, { sessionRequired: false })
if (session !== undefined) { let userId = session.getUserId(); } else { // user is not logged in... }
//... }})
import Fastify from "fastify";import Session from "supertokens-node/recipe/session";
let fastify = Fastify();
fastify.post("/like-comment", async (req, res) => { let session = await Session.getSession(req, res, { sessionRequired: false })
if (session !== undefined) { let userId = session.getUserId(); } else { // user is not logged in... } //....});
import Session from "supertokens-node/recipe/session";import { middleware } from "supertokens-node/framework/awsLambda";import { SessionEvent } from "supertokens-node/framework/awsLambda";
async function likeComment(awsEvent: SessionEvent) { let session = await Session.getSession(awsEvent, awsEvent, { sessionRequired: false })
if (session !== undefined) { let userId = session.getUserId(); } else { // user is not logged in... }
//....};
exports.handler = middleware(likeComment);
import KoaRouter from "koa-router";import Session from "supertokens-node/recipe/session";
let router = new KoaRouter();
router.post("/like-comment", async (ctx, next) => { let session = await Session.getSession(ctx, ctx, { sessionRequired: false })
if (session !== undefined) { let userId = session.getUserId(); } else { // user is not logged in... }
//....});
import { inject } from "@loopback/core";import { RestBindings, MiddlewareContext, post, response } from "@loopback/rest";import Session from "supertokens-node/recipe/session";
class LikeComment {
constructor(@inject(RestBindings.Http.CONTEXT) private ctx: MiddlewareContext) { } @post("/like-comment") @response(200) async handler() { let session = await Session.getSession(this.ctx, this.ctx, { sessionRequired: false })
if (session !== undefined) { let userId = session.getUserId(); } else { // user is not logged in... }
//.... }}
import { superTokensNextWrapper } from 'supertokens-node/nextjs'import Session from "supertokens-node/recipe/session";import { SessionRequest } from "supertokens-node/framework/express";
export default async function likeComment(req: SessionRequest, res: any) { let session = await superTokensNextWrapper( async (next) => { return await Session.getSession(req, res, { sessionRequired: false }); }, req, res )
if (session !== undefined) { let userId = session.getUserId(); } else { // user is not logged in... } //....}
import { Controller, Post, UseGuards, Req, Res } from "@nestjs/common";import type { Request, Response } from "express";import { AuthGuard } from './auth/auth.guard';import Session from "supertokens-node/recipe/session";
@Controller()export class ExampleController { @Post('example') @UseGuards(AuthGuard) async postExample(@Req() req: Request, @Res({ passthrough: true }) res: Response): Promise<boolean> { // This should be done inside a parameter decorator, for more information please read our NestJS guide. const session = await Session.getSession(req, res, { sessionRequired: false })
if (session !== undefined) { const userId = session.getUserId(); } else { // user is not logged in... } //.... return true; }}
import ( "fmt" "net/http"
"github.com/supertokens/supertokens-golang/recipe/session" "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" "github.com/supertokens/supertokens-golang/supertokens")
func likeCommentAPI(w http.ResponseWriter, r *http.Request) { sessionRequired := false sessionContainer, err := session.GetSession(r, w, &sessmodels.VerifySessionOptions{ SessionRequired: &sessionRequired, })
if err != nil { err = supertokens.ErrorHandler(err, r, w) if err != nil { // TODO: send 500 to client } return } if sessionContainer != nil { // session exists userID := sessionContainer.GetUserID() fmt.Println(userID) } else { // user is not logged in }}
- FastAPI
- Flask
- Django
from supertokens_python.recipe.session.asyncio import get_sessionfrom fastapi import Request
@app.post('/like-comment') async def like_comment(request: Request): session = await get_session(request, session_required=False)
if session is not None: user_id = session.get_user_id() print(user_id) # TODO: else: pass # user is not logged in
from supertokens_python.recipe.session.syncio import get_sessionfrom flask.wrappers import Request
@app.route('/like-comment', methods=['POST']) def like_comment(request: Request): session = get_session(request, session_required=False)
if session is not None: user_id = session.get_user_id() print(user_id) # TODO.. else: pass # user is not logged in
from django.http import HttpRequestfrom supertokens_python.recipe.session.asyncio import get_session
async def like_comment(request: HttpRequest): session = await get_session(request, session_required=False)
if session is not None: user_id = session.get_user_id() print(user_id) # TODO.. else: pass # user is not logged in