Skip to content
Skip to content
Menu
A cup of dev
  • Home
  • About
  • Contact
  • Books and ink
A cup of dev

How to leverage teams-js in your Teams app; Working with user context and SharePoint site context

By Eli H. Schei on Thursday, 22 February 2024, 7:00Thursday, 22 February 2024, 9:43

When developing apps for Microsoft Teams, you often need to know the associated SharePoint sites, and the current user’s details. This will help you retrieve relevant info, and create personalized user experiences.
In this blogpost, I will delve into how to leverage teams-js, a powerful toolset enabling developers to effortlessly access and harness this information through the context object.

Prerequesites: I won’t cover how to build apps for teams, just how to leverage teams-js inside your existing app. See the section for resources in the bottom of this blogpost for resources on how to build apps for MS Teams.

Table of contents

  • Adding and using teams-js in your project
  • Use the info from the context to get even more info via MS Graph
  • Summary
  • Resources

Adding and using teams-js in your project

Install teams-js npm package

npm install @microsoft/teams-js

Import the app object in the file where you want to use the context

import { app } from "@microsoft/teams-js";

Leverage teams-js context objects

First you need to initialize the object. And then you can use the getContect() to get the different context objects.

app.initialize();

const currentContext= await app.getContext().then(context => context);
const currentUser = currentContext.user;
const currentSPsite = currentContext.sharePointSite

From the currentSPSite context you can get info about the SharePoint site associated with the team, and you can access info about the site domain, site ID and path/url.

From the currentUser context you can access information about the current user, like display name, user principal name and id (MS Entra object id).

Here is an example of using the context to get the current users name and displaying it in your app.

import * as React from 'react';
import { app } from "@microsoft/teams-js";

const sampleComponent :React.FC<sampleProps> = () => {
//...
      const username =await app.getContext().then((context) => context.user?.displayName);
//...
   return (
      <div>
        <h2>Hello {username}/h2>
      </div>
    );
}

Use context info to get even more info via MS Graph

Note: For this part you need to add authentication. I won’t cover how to do this in this blogpost.You can take a look at these previus blogposts about the topic, or use a SDK.

Lets say you would like to update a SharePoint list from inside your app. And the list lives in the SharePoint site of the team. To make the app work accross teams you need to be able to get the SharePoint site info dynamically. This is a good usecase for using the teams-js context.

Lets look at an example where you would like to view, edit or add files to the document libary in the accossiated SharePoint site.

Firts you need to get the context object for the SharePoint site.

const currentSPContext= await app.getContext().then(context => context.sharePointSite);

Then you can use this info and graph to get the site_id_url for your SharePoint site.

When talkting with graph you often need to use the site-id which is a combination of <your_domain, some_id, some_other_id>. The easiest way is to use graph to get this ID dynamically as well.

const site_id_url = `https://graph.microsoft.com/v1.0/sites/${currentSPContext.teamSiteDomain}:/${currentSPContext.teamSitePath}$select=id`
const site_id = await fetch(site_id_url, {
  method: "GET",
  headers: {
    // NOTE! You need to add a bearer token
    Authorization: `Bearer ${token}`,
  },
})
.then((response) => response.json()).then(data => data.id)

When you have the site-id you can use to perform CRUD operations against the document library.

For more details about uploading a file, or updating a field – see my previous blogposts on the subject.

const documentLibraryUrl = `https://graph.microsoft.com/v1.0/sites/${site_id}/drive`;

// Upload file. Note: Graph will accept the file as an ArrayBuffer, a Buffer or a Blob
const uploadDocument= (filename, fileToUpload) => {
  const uploadURL = `${documentLibraryUrl }/drive/root:/${filename}:/content`;
    await window
    .fetch(uploadURL, {
      method: "PUT",
      headers: {
        Authorization: `Bearer ${token}`,
      },
      body: fileToUpload,
    })
    .then((response) => {
        // Here you can implement some user feedback. "File uploaded" etc.. 
    })
    .catch((error) => {
      console.error("ERROR UPLOADING");
      console.error(error);
    });
}

//Update field values
const updateFields = (fieldUpdateValues) => {
   const updateURL = `https://graph.microsoft.com/v1.0/sites/${site_id}/lists/<LIST_ID>/items/<ITEM_ID>/fields`;
await fetch(updateURL, {
      method: "PATCH",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(fieldUpdateValues),
    })
    .then((response) => response.json())
    .then((data) => {
      console.log("Update success");
    })
    .catch((error) => {
      console.error("ERROR");
      console.error(error);
    });
}

Summary

In this blogpost we looked at how to use teams-js to access context objects with info about the current user, and the Teams associated SharePoint site. You can use this info to create personalized user experiences.

We have also looked at how to use the information to leverage Graph to get more info, and do CRUD operations on a document library.

Resources

  • Create apps for teams using Teams toolkit (Microsoft docs)
  • Building Microsft Teams Tabs using SPfx (Microsoft docs)
  • Microsoft Graph (Microsoft docs)
  • Upload files to SharePoint using MS Graph and MSAL (blogpost)
  • Update field values in SharePoint using MS Graph (blogpost)

Did you find this article usefull? Follow me on twitter to be notified when I publish something new!

If you are interested in Microsoft 365 Development you might also like my other blogposts in this category.

Also, if you have any feedback or questions, please let me know in the comments below. 🙂

Thank you for reading, and happy coding!

/Eli

If you want to support my content you can

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Post navigation

Building a ‘My Tools’ Web Part for SharePoint: Using SPfx and PnPjs
Microsoft Graph Magic: Simplifying User Removal from teams in Microsoft Teams

Leave a ReplyCancel reply

Eli H. Schei

I'm a front-end developer who mainly work in the Microsoft 365-sphere. As a developer I read a lot of blogs. And in my experience I can read multiple different blogposts about exactly the same topic, and only one of them makes sense to me. Therefore I’m adding my voice to the mix, and hopefully one of my blogposts will be the one that makes sense of a topic for you. You can learn more about me here.

Recent Posts

  • React in ListViewCommandSet – how to fix the “Cannot read properties of undefined (reading ‘id’)” error
  • How to Get Site-ID with Graph Explorer (and other SharePoint info)
  • How to use Azure CLI to deploy Azure Functions: Step-by-Step Guide
  • Give your app granular permissions to a specific site or list in SharePoint
  • Microsoft Graph Magic: Simplifying User Removal from teams in Microsoft Teams

Categories

  • Azure
    • Azure CLI
    • Azure functions
  • Level
    • Beginner
    • Intermediate
  • Microsoft 365 Development
    • Microsoft Authentication Library
    • Microsoft Graph
    • Microsoft Teams
    • PNP powershell
    • PowerApps
      • PowerApps Component Framework
    • SharePoint Framework
    • SharePoint Online
  • Tech Lead
  • Web development
    • Accessibility
    • Soft skills
    • Tips and tricks

Tags

accessibility app permissions ARIA azure Azure CLI azure functions Content creation custom themes favorites git github ListViewCommandSet M365 CLI M365 development MS Graph PCF PnPjs PnP powershell power apps PowerApps Component Framework quicktip react resources SharePoint Online Sideloading SPfx Teams teams app dev Teams apps Tech lead tools wcag webdev Windows terminal
©2025 A cup of dev | WordPress Theme by SuperbThemes.com