Creating a new session
#
How to create a new sessionCreate a new session after verifying user's credentials in the login API, or after creating a new user in the sign up API.
- 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("/login", async (req, res) => {
// verify user's credentials...
let userId = "userId"; // get from db
await Session.createNewSession(res, userId);
/* a new session has been created. * - an access & refresh token has been attached to the response's cookie * - a new row has been inserted into the database for this new session */
res.json({ message: "User logged in!" });})
import Hapi from "@hapi/hapi";import Session from "supertokens-node/recipe/session";
let server = Hapi.server({ port: 8000 });
server.route({ path: "/login", method: "post", handler: async (req, res) => { // verify user's credentials...
let userId = "userId"; // get from db
await Session.createNewSession(res, userId);
/* a new session has been created. * - an access & refresh token has been attached to the response's cookie * - a new row has been inserted into the database for this new session */ return res.response({ message: "User logged in!" }).code(200); },});
import Fastify from "fastify";import Session from "supertokens-node/recipe/session";
let fastify = Fastify();
fastify.post("/login", async (req, res) => {
// verify user's credentials...
let userId = "userId"; // get from db
await Session.createNewSession(res, userId);
/* a new session has been created. * - an access & refresh token has been attached to the response's cookie * - a new row has been inserted into the database for this new session */
res.send({ message: "User logged in!" });})
import { middleware } from "supertokens-node/framework/awsLambda"import Session from "supertokens-node/recipe/session";import { SessionEvent } from "supertokens-node/framework/awsLambda";
async function login(awsEvent: SessionEvent) { // verify user's credentials...
let userId = "userId"; // get from db
await Session.createNewSession(awsEvent, userId);
/* a new session has been created. * - an access & refresh token has been attached to the response's cookie * - a new row has been inserted into the database for this new session */
return { body: JSON.stringify({ message: "User logged in!" }), statusCode: 200, };}
exports.handler = middleware(login);
import KoaRouter from "koa-router";import Session from "supertokens-node/recipe/session";
let router = new KoaRouter();
router.post("/login", async (ctx, next) => {
// verify user's credentials...
let userId = "userId"; // get from db
await Session.createNewSession(ctx, userId);
/* a new session has been created. * - an access & refresh token has been attached to the response's cookie * - a new row has been inserted into the database for this new session */
ctx.body = { message: "User logged in!" };})
import { inject } from "@loopback/core";import { RestBindings, MiddlewareContext, post, response } from "@loopback/rest";import Session from "supertokens-node/recipe/session";
class Login { constructor(@inject(RestBindings.Http.CONTEXT) private ctx: MiddlewareContext) { } @post("/login") @response(200) async handler() { // verify user's credentials...
let userId = "userId"; // get from db
await Session.createNewSession(this.ctx, userId); return { message: "User logged in!" }; }}
import { superTokensNextWrapper } from 'supertokens-node/nextjs'import { createNewSession } from "supertokens-node/recipe/session";import { SessionRequest } from "supertokens-node/framework/express";
export default async function superTokens(req: SessionRequest, res: any) { // verify user's credentials...
let userId = "userId"; // get from db await superTokensNextWrapper( async (next) => { await createNewSession(req, userId); }, req, res ); res.json({ message: "User logged in!" });}
import { Controller, Post, Res } from "@nestjs/common";import type { Response } from "express";import { createNewSession } from "supertokens-node/recipe/session";
@Controller()export class ExampleController { // For more information about "AuthGuard" and the "Session" decorator please read our NestJS guide. @Post("login") async postLogin(@Res() res: Response): Promise<{ message: string }> { let userId = "userId"; // get from db
await createNewSession(res, userId);
/* a new session has been created. * - an access & refresh token has been attached to the response's cookie * - a new row has been inserted into the database for this new session */
return { message: "User logged in!" }; }}
import ( "net/http"
"github.com/supertokens/supertokens-golang/recipe/session" "github.com/supertokens/supertokens-golang/supertokens")
func login(w http.ResponseWriter, r *http.Request) {
// verify user's credentials...
userId := "userId" // get from db
_, err := session.CreateNewSession(w, userId, nil, nil) if err != nil { err = supertokens.ErrorHandler(err, r, w) if err != nil { // Send 500 to client } }
/* a new session has been created. * - an access & refresh token has been attached to the response's cookie * - a new row has been inserted into the database for this new session */
// Send 200 success to client}
- FastAPI
- Flask
- Django
from supertokens_python.recipe.session.asyncio import create_new_sessionfrom fastapi import Requestfrom fastapi.responses import JSONResponse
@app.post('/login') async def login(request: Request): # verify user's credentials...
user_id = "..." # get from db
await create_new_session(request, user_id)
# a new session has been created. # - an access & refresh token has been attached to the response's cookie # - a new row has been inserted into the database for this new session #
return JSONResponse({"message": "User logged in!"})
from supertokens_python.recipe.session.syncio import create_new_sessionfrom flask import jsonifyfrom flask.wrappers import Request
@app.route('/login', methods=['POST']) def login(request: Request): # verify user's credentials...
user_id = "..." # get from db
create_new_session(request, user_id)
# a new session has been created. # - an access & refresh token has been attached to the response's cookie # - a new row has been inserted into the database for this new session #
return jsonify({"message": "User logged in!"})
from supertokens_python.recipe.session.asyncio import create_new_sessionfrom django.http import HttpRequest, JsonResponse
async def login(request: HttpRequest): # verify user's credentials...
user_id = "..." # get from db
await create_new_session(request, user_id)
# a new session has been created. # - an access & refresh token has been attached to the response's cookie # - a new row has been inserted into the database for this new session #
return JsonResponse({"message": "User logged in!"})