Home Web Front-end JS Tutorial Building Social Media Automation: LinkedIn Sharing with Serverless Function

Building Social Media Automation: LinkedIn Sharing with Serverless Function

Jan 08, 2025 pm 04:33 PM

After publishing a new article or blog post, the need to promote it on social media arises. Manually sharing the post can be time-consuming and inefficient. In this article, we will explore how to build a serverless function to share an article URL on LinkedIn using its JavaScript API client and Netlify serverless functions. This is part of building an automated workflow for social media promotion.

Table of Contents

  • Table of Contents
  • Prerequisites
  • Getting started
    • Setting up the permissions
    • Configuring OAuth 2.0 settings
  • Sharing a post with URL using LinkedIn API JS Client
    • Getting the user's unique id
    • Sharing a post URL
  • Exposing as a Netlify serverless function
  • Testing the Functionality
  • Deploying with Netlify
  • Summary

Prerequisites

To follow along with this tutorial, you will need the following:

  • A LinkedIn account
  • Node.js and Netlify CLI installed.
  • A Netlify account and a site created for deploying the serverless function.
  • Basic knowledge of JavaScript and TypeScript.

Getting started

To start working with LinkedIn APIs, we need to perform the following steps:

  1. Head to LinkedIn Developer Console with your LinkedIn account.
  2. Create a new app by clicking on the Create App button. Building Social Media Automation: LinkedIn Sharing with Serverless Function
  3. Fill in the details such as App Name (Social Media Tester, for example) and App logo image.
  4. You will need to a LinkedIn Company page to associate with the app you are creating (any page you have admin access to be able to verify the connection afterwards).

Building Social Media Automation: LinkedIn Sharing with Serverless Function

Once done, the portal will redirect you to the app dashboard, where we can start configuring the permissions and API products we need for the app.

Building Social Media Automation: LinkedIn Sharing with Serverless Function

Setting up the permissions

In the app dashboard, click on Products tabs and request access to the Share on LinkedIn and Sign In with LinkedIn using OpenID Connect products.

Building Social Media Automation: LinkedIn Sharing with Serverless Function

Configuring OAuth 2.0 settings

With these permissions granted, we can head to the OAuth 2.0 token generator tool to generate an access token for the app. The token should include the following scopes: w_member_social for posting on behalf of the user, and profile and openid for user authentication and profile information.

Building Social Media Automation: LinkedIn Sharing with Serverless Function

This access token is a 3-legged OAuth token, ensuring that the user has explicitly authorized the application to act on their behalf. After generating the token, we can use it to authenticate and securely make requests to the LinkedIn APIs. Additionally, we can review the permissions and scopes granted to the app in the Auth tab of the app dashboard.

Great! Now that we have the access token and the app set up, we can start building the automation to post on LinkedIn on behalf of the user (which, in this case, is us).

Sharing a post with URL using LinkedIn API JS Client

To start sharing posts programmatically, we can use the official LinkedIn API JavaScript Client for Node.js by installing it as a project dependency:

npm install linkedin-api-js-client

# or with yarn
yarn add linkedin-api-js-client
Copy after login
Copy after login
Copy after login

This library provides a straightforward and lightweight way to interact with LinkedIn API endpoints, leveraging Axios and TypeScript under the hood.

Next, let's create a new file, linkedin.ts, to encapsulate the logic for sharing posts on LinkedIn. We start by initializing a client instance to interact with the API, as shown below:

// linkedin.ts
import { RestliClient } from 'linkedin-api-js-client';

const client = new RestliClient();
Copy after login
Copy after login

Getting the user's unique id

To post on behalf of a user, we first need to retrieve the user's unique ID (which is different from the user's LinkedIn handle). This can be done by using the /userinfo endpoint with the access token generated earlier:

// linkedin.ts
const getUserId = async (accessToken: string) => {
  const userResponse = await client.get({
    resourcePath: "/userinfo",
    accessToken
  });

  return userResponse.data?.sub;
};
Copy after login
Copy after login

The unique ID is located in the sub field of the response's data. This value is required for the next step: sharing a post on the user's behalf.

Sharing a post URL

Within linkedin.ts, we define a function to share a post's URL as follows:

type SharePostArgs = {
  url: string;
  text: string;
};

export const sharePost = async (token: string, content: SharePostArgs) => {
  //logic
};
Copy after login
Copy after login

The sharePost function takes the access token and the content to share, which includes the URL and the text to accompany the post. We will then create a new post entity on the User Generated Contents resource using /ugcPosts endpoint, as shown below:

export const sharePost = async (token: string, content: SharePostArgs) => {
  const response = await client.create({
    resourcePath: '/ugcPosts',
    accessToken: token,
    entity: {
      //entity payload
    }
  });
};
Copy after login
Copy after login

The entity payload is configured to include the user’s unique ID, retrieved earlier, as the author. The author field follows the format urn:li:person:${userId}. Additionally, we specify:

  • The lifecycleState as "PUBLISHED".
  • The visibility as "PUBLIC" so the post is visible to the LinkedIn network.

Here’s the updated implementation:

npm install linkedin-api-js-client

# or with yarn
yarn add linkedin-api-js-client
Copy after login
Copy after login
Copy after login

Next, we define the sharing content within the specificContent field of the entity object. For this scenario, the specificContent field includes a com.linkedin.ugc.ShareContent object, which has the following properties:

  • shareCommentary: Accepts content.text as the main text content to display.
  • shareMediaCategory: Specifies the type of media shared in the post (set as "ARTICLE").
  • media: An array of media assets for the "ARTICLE" category, where each item includes: the URL to share and a READY status.

Below is the updated code:

// linkedin.ts
import { RestliClient } from 'linkedin-api-js-client';

const client = new RestliClient();
Copy after login
Copy after login

Upon successfully completing the request, the response contains a createdEntityId, representing the unique ID of the created entity. We can return this value to the caller for further reference:

// linkedin.ts
const getUserId = async (accessToken: string) => {
  const userResponse = await client.get({
    resourcePath: "/userinfo",
    accessToken
  });

  return userResponse.data?.sub;
};
Copy after login
Copy after login

And that's it! We’ve created a function that leverages the LinkedIn API to share a post URL on behalf of a user. In the next step, we’ll expose this function as a serverless endpoint using Netlify, bringing us closer to fully automating the process of sharing articles on social media.

Exposing as a Netlify serverless function

We run the CLI command netlify functions:create and follow the prompts to scaffold a new Netlify serverless function named share-on-linkedin. The Netlify CLI will generate the function in the functions directory with the following initial code:

type SharePostArgs = {
  url: string;
  text: string;
};

export const sharePost = async (token: string, content: SharePostArgs) => {
  //logic
};
Copy after login
Copy after login

In this above code, we use TypeScript and define the function as async to handle the asynchronous nature of LinkedIn API calls.

Next, we update the serverless function to perform the following actions:

  • Parse the request body to extract the content to share,
  • Retrieve the access token from environment variables (can be set in .env file in the project root),
  • Call the sharePost function (defined earlier in linkedin.ts ) with the extracted parameters, and
  • Return the created entity ID as the response.
export const sharePost = async (token: string, content: SharePostArgs) => {
  const response = await client.create({
    resourcePath: '/ugcPosts',
    accessToken: token,
    entity: {
      //entity payload
    }
  });
};
Copy after login
Copy after login

At this point, the serverless function is ready. We can deploy it to Netlify and test its functionality by making POST requests to the endpoint.

Testing the Functionality

To test the serverless function, start a local server using the CLI command netlify dev. Then, use a tool like Postman or Insomnia to send a POST request to the server endpoint with the following JSON payload:

export const sharePost = async (token: string, content: SharePostArgs) => {
  //Get user's unique id
  const userId = await getUserId(token);

  const response = await client.create({
    resourcePath: '/ugcPosts',
    accessToken: token,
    entity: {
      author: `urn:li:person:${userId}`,
      lifecycleState: "PUBLISHED",      
      visibility: {
        "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
      }
    }
  });
};
Copy after login

Alternatively, we can create a simple form UI to interact with the serverless function API, and verify that the post is successfully shared on LinkedIn.

Once the function is working as expected, let's proceed to deploy it to Netlify to make it available for use.

Deploying with Netlify

To deploy our function to Netlify, run the following command:

npm install linkedin-api-js-client

# or with yarn
yarn add linkedin-api-js-client
Copy after login
Copy after login
Copy after login

The CLI deploys the function to your Netlify production environment. You can then find the function endpoint in the Netlify dashboard.

Important: Make sure to configure the LINKEDIN_ACCESS_TOKEN environment variable in the dashboard. This step is essential for the function to authenticate and operate correctly.

Building Social Media Automation: LinkedIn Sharing with Serverless Function


Summary

We have successfully built a serverless API to share an article URL on LinkedIn on behalf of a user, leveraging the LinkedIn API JavaScript Client and Netlify serverless functions. This marks a significant step toward automating the social media sharing process for blog posts.

From here, we can extend the automation workflow to include other social media platforms and scheduled tasks. For example, we could integrate platforms like X (formerly Twitter), Facebook, or BlueSky, and customize the timing and content of posts to maximize audience engagement and reach.

With that, stay tuned for more updates on this series!

? Learn about Vue 3 and TypeScript with my new book Learning Vue!

? Want to support me? Buy me a coffee.

Like this post or find it helpful? Share it ?

The above is the detailed content of Building Social Media Automation: LinkedIn Sharing with Serverless Function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles