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.
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
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