Get User Info
You can fetch user information on the backend as well as on the frontend.
#
Fetching on the backendgetUserByEmail
#
Using - NodeJS
- GoLang
- Python
You can get a user's information on the backend using the getUsersByEmail
, getUserByPhoneNumber
and getUserById
functions:
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
async function handler() {
const userInfo = await ThirdPartyPasswordless.getUsersByEmail("test@example.com");
}
You can get a user's information on the backend using the GetUserByEmail
, GetUserByPhoneNumber
and GetUserById
functions:
import (
"fmt"
"github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless"
)
func main() {
userInfo, err := thirdpartypasswordless.GetUsersByEmail("test@example.com")
if err != nil {
// TODO: Handle error
return
}
fmt.Println(userInfo)
//...
}
- Asyncio
- Syncio
from supertokens_python.recipe.thirdpartypasswordless.asyncio import get_users_by_email
async def some_func():
_ = await get_users_by_email("test@example.com")
from supertokens_python.recipe.thirdpartypasswordless.syncio import get_users_by_email
user_info = get_users_by_email("test@example.com")
getUserByPhoneNumber
#
Using - NodeJS
- GoLang
- Python
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
async function handler() {
const userInfo = await ThirdPartyPasswordless.getUserByPhoneNumber({phoneNumber: "+1234567891"});
}
import (
"fmt"
"github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless"
)
func main() {
userInfo, err := thirdpartypasswordless.GetUserByPhoneNumber("+1234567890")
if err != nil {
// TODO: Handle error
return
}
fmt.Println(userInfo)
//...
}
- Asyncio
- Syncio
from supertokens_python.recipe.thirdpartypasswordless.asyncio import get_user_by_phone_number
async def some_func():
_ = await get_user_by_phone_number("+1234567890")
from supertokens_python.recipe.thirdpartypasswordless.syncio import get_user_by_phone_number
user_info = get_user_by_phone_number("+1234567890")
getUserById
#
Using - NodeJS
- GoLang
- Python
- Express
- Hapi
- Fastify
- Koa
- Loopback
- AWS Lambda / Netlify
- Next.js
- NestJS
import express from "express";
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
import { verifySession } from "supertokens-node/recipe/session/framework/express";
const app = express();
app.get("/get-user-info", verifySession(), async (req, res) => {
let userId = req.session.getUserId();
let userInfo = await ThirdPartyPasswordless.getUserById(userId)
// ...
})
import Hapi, { Request } from "@hapi/hapi";
const server = Hapi.server();
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
import { SessionContainer } from "supertokens-node/recipe/session";
import { verifySession } from "supertokens-node/recipe/session/framework/hapi";
server.route({
path: "/get-user-info",
method: "get",
options: {
pre: [
{
method: verifySession()
},
],
},
handler: async (req: Request & { session: SessionContainer}, res) => {
let userId = req.session.getUserId();
let userInfo = await ThirdPartyPasswordless.getUserById(userId);
//...
}
})
import Fastify from "fastify";
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
import { verifySession } from "supertokens-node/recipe/session/framework/fastify";
const fastify = Fastify();
fastify.post("/like-comment", {
preHandler: verifySession(),
}, async (req, res) => {
let userId = req.session.getUserId();
let userInfo = await ThirdPartyPasswordless.getUserById(userId);
//....
});
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
import { SessionEventV2 } from "supertokens-node/framework/awsLambda";
import { verifySession } from "supertokens-node/recipe/session/framework/awsLambda";
async function getUserInfo(awsEvent: SessionEventV2, _: any) {
let userId = awsEvent.session!.getUserId();
let userInfo = await ThirdPartyPasswordless.getUserById(userId);
//....
};
exports.handler = verifySession(getUserInfo);
import KoaRouter from "koa-router";
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
import { verifySession } from "supertokens-node/recipe/session/framework/koa";
const router = new KoaRouter();
router.get("/get-user-info", verifySession(), async (ctx, next) => {
let userId = ctx.session!.getUserId();
let userInfo = await ThirdPartyPasswordless.getUserById(userId);
//....
});
import { inject, intercept } from '@loopback/core';
import { get, response, MiddlewareContext, RestBindings } from '@loopback/rest';
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
import { verifySession } from "supertokens-node/recipe/session/framework/loopback";
import Session from "supertokens-node/recipe/session";
class GetUserInfo {
constructor(@inject(RestBindings.Http.CONTEXT) private ctx: MiddlewareContext) {}
@get("/get-user-info")
@intercept(verifySession())
@response(200)
async handler() {
let userId = ((this.ctx as any).session as Session.SessionContainer).getUserId();
let userInfo = await ThirdPartyPasswordless.getUserById(userId);
//....
}
}
import { SessionRequest } from 'supertokens-node/framework/express';
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
import { superTokensNextWrapper } from 'supertokens-node/nextjs'
import { verifySession } from "supertokens-node/recipe/session/framework/express";
export default async function likeComment(req: SessionRequest, res: any) {
await superTokensNextWrapper(
async (next) => {
await verifySession()(req, res, next);
},
req,
res
)
let userId = req.session!.getUserId();
let userInfo = await ThirdPartyPasswordless.getUserById(userId);
//....
}
import { Controller, Post, UseGuards, Session } from '@nestjs/common';
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
import { SessionContainer } from "supertokens-node/recipe/session";
import { AuthGuard } from './auth/auth.guard';
@Controller()
export class ExampleController {
@Post('example')
@UseGuards(new AuthGuard()) // For more information about this guard please read our NestJS guide.
async postExample(@Session() session: SessionContainer): Promise<boolean> {
let userId = session.getUserId();
let userInfo = await ThirdPartyPasswordless.getUserById(userId);
//....
return false;
}
}
- Chi
- net/http
- Gin
- Mux
import (
"fmt"
"net/http"
"github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless"
"github.com/supertokens/supertokens-golang/recipe/session"
)
func main() {
_ = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
session.VerifySession(nil, getUserInfoAPI).ServeHTTP(rw, r)
})
}
func getUserInfoAPI(w http.ResponseWriter, r *http.Request) {
sessionContainer := session.GetSessionFromRequestContext(r.Context())
userID := sessionContainer.GetUserID()
userInfo, err := thirdpartypasswordless.GetUserByID(userID)
if err != nil {
// TODO: Handle error
return
}
fmt.Println(userInfo)
}
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless"
"github.com/supertokens/supertokens-golang/recipe/session"
"github.com/supertokens/supertokens-golang/recipe/session/sessmodels"
)
func main() {
router := gin.New()
router.GET("/getuserinfo", verifySession(nil), getUserInfoAPI)
}
func verifySession(options *sessmodels.VerifySessionOptions) gin.HandlerFunc {
return func(c *gin.Context) {
session.VerifySession(options, func(rw http.ResponseWriter, r *http.Request) {
c.Request = c.Request.WithContext(r.Context())
c.Next()
})(c.Writer, c.Request)
// we call Abort so that the next handler in the chain is not called, unless we call Next explicitly
c.Abort()
}
}
func getUserInfoAPI(c *gin.Context) {
sessionContainer := session.GetSessionFromRequestContext(c.Request.Context())
userID := sessionContainer.GetUserID()
userInfo, err := thirdpartypasswordless.GetUserByID(userID)
if err != nil {
// TODO: Handle error
return
}
fmt.Println(userInfo)
//...
}
import (
"fmt"
"net/http"
"github.com/go-chi/chi"
"github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless"
"github.com/supertokens/supertokens-golang/recipe/session"
)
func main() {
r := chi.NewRouter()
r.Get("/getuserinfo", session.VerifySession(nil, getUserInfoAPI))
}
func getUserInfoAPI(w http.ResponseWriter, r *http.Request) {
sessionContainer := session.GetSessionFromRequestContext(r.Context())
userID := sessionContainer.GetUserID()
userInfo, err := thirdpartypasswordless.GetUserByID(userID)
if err != nil {
// TODO: Handle error
return
}
fmt.Println(userInfo)
}
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless"
"github.com/supertokens/supertokens-golang/recipe/session"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/getuserinfo", session.VerifySession(nil, getUserInfoAPI)).Methods(http.MethodGet)
}
func getUserInfoAPI(w http.ResponseWriter, r *http.Request) {
sessionContainer := session.GetSessionFromRequestContext(r.Context())
userID := sessionContainer.GetUserID()
userInfo, err := thirdpartypasswordless.GetUserByID(userID)
if err != nil {
// TODO: Handle error
return
}
fmt.Println(userInfo)
}
- FastAPI
- Flask
- Django
from supertokens_python.recipe.session.framework.fastapi import verify_session
from supertokens_python.recipe.thirdpartypasswordless.asyncio import get_user_by_id
from supertokens_python.recipe.session import SessionContainer
from fastapi import Depends
@app.post('/get_user_info_api')
async def get_user_info_api(session: SessionContainer = Depends(verify_session())):
user_id = session.get_user_id()
_ = await get_user_by_id(user_id)
from supertokens_python.recipe.session.framework.flask import verify_session
from supertokens_python.recipe.thirdpartypasswordless.syncio import get_user_by_id
from supertokens_python.recipe.session import SessionContainer
from flask import g
@app.route('/update-jwt', methods=['POST'])
@verify_session()
def get_user_info_api():
session: SessionContainer = g.supertokens
user_id = session.get_user_id()
_ = get_user_by_id(user_id)
from supertokens_python.recipe.session.framework.django.asyncio import verify_session
from supertokens_python.recipe.thirdpartypasswordless.asyncio import get_user_by_id
from django.http import HttpRequest
from supertokens_python.recipe.session import SessionContainer
@verify_session()
async def get_user_info_api(request: HttpRequest):
session: SessionContainer = request.supertokens
user_id = session.get_user_id()
_ = await get_user_by_id(user_id)
#
Fetching on the frontendimportant
The function calls below require no API calls and read directly from the session information stored on the frontend. This makes them very quick.
- ReactJS
- Angular
- Vue
- Plain JavaScript
- React Native
import Session from 'supertokens-web-js/recipe/session';
async function handle() {
if (await Session.doesSessionExist()) {
let userId = await Session.getUserId();
let accessTokenPayload = await Session.getAccessTokenPayloadSecurely();
}
}
- With React Context
- Without React Context
import React from "react";
import { useSessionContext } from 'supertokens-auth-react/recipe/session';
// Your dashboard component
function Dashboard(props: any) {
let session = useSessionContext();
if (session.loading) {
return null;
}
if (!session.doesSessionExist) {
// TODO
} else {
let {userId, accessTokenPayload} = session;
let name = accessTokenPayload.name;
}
}
import Session from 'supertokens-auth-react/recipe/session';
async function handle() {
if (await Session.doesSessionExist()) {
let userId = await Session.getUserId();
let accessTokenPayload = await Session.getAccessTokenPayloadSecurely();
}
}
- Via NPM
- Via Script Tag
import Session from 'supertokens-web-js/recipe/session';
async function handle() {
if (await Session.doesSessionExist()) {
let userId = await Session.getUserId();
let accessTokenPayload = await Session.getAccessTokenPayloadSecurely();
}
}
async function handle() {
if (await supertokensSession.doesSessionExist()) {
let userId = await supertokensSession.getUserId();
let accessTokenPayload = await supertokensSession.getAccessTokenPayloadSecurely();
}
}
import SuperTokens from 'supertokens-react-native';
async function handle() {
if (await SuperTokens.doesSessionExist()) {
let userId = await SuperTokens.getUserId();
let accessTokenPayload = await SuperTokens.getAccessTokenPayloadSecurely();
}
}
import Session from 'supertokens-web-js/recipe/session';
async function handle() {
if (await Session.doesSessionExist()) {
let userId = await Session.getUserId();
let accessTokenPayload = await Session.getAccessTokenPayloadSecurely();
}
}