facebook-business
v2.0.0
Published
Cookie-backed Facebook Business Graph helpers for Node.js.
Readme
facebook-business
Cookie-backed Facebook Business Graph helpers for Node.js.
This package discovers a usable Facebook Business session from a trusted server-side cookie, extracts available access tokens, and wraps common Facebook Graph workflows for groups, pages, comments, reactions, and media uploads.
Use it for backend jobs, internal automation, workflow runners, and private admin tools. Do not expose Facebook cookies to browsers, client bundles, logs, analytics, or untrusted users.
Features
- Normalize raw Facebook cookie headers or browser-exported cookie JSON.
- Discover Facebook Business session metadata and available access tokens.
- Read Facebook group info and group feed posts.
- Create text, image, and video posts in groups.
- Read post comments, create comments, and set reactions.
- Sync managed pages and resolve page access tokens.
- Read page info and page posts.
- Create text, image, and video posts on pages.
- Upload photos from remote URLs.
- Fully typed TypeScript API with CommonJS output.
Requirements
- Node.js 18 or newer.
- A valid Facebook cookie from an account that has permission for the target group or page.
- Server-side execution only.
Install
npm install facebook-businessThen import it in your backend code:
import { createFacebookBusinessClient } from "facebook-business"Environment
Store the cookie in an environment variable:
FB_BUSINESS_COOKIE='c_user=...; xs=...'
FB_GRAPH_VERSION='v24.0'Optional:
FB_USER_AGENT='Mozilla/5.0 ...'The cookie can be either:
- a raw
Cookieheader string - a JSON export with a
cookies[]array containing{ name, value }items
Only the cookies needed for Facebook requests are retained by the normalizer.
Quick Start
import { createFacebookBusinessClient } from "facebook-business"
const facebook = createFacebookBusinessClient({
cookie: process.env.FB_BUSINESS_COOKIE || "",
graphVersion: process.env.FB_GRAPH_VERSION || "v24.0",
userAgent: process.env.FB_USER_AGENT,
})
const posts = await facebook.getGroupPosts({
groupId: "123456789",
limit: 10,
hoursBack: 24,
})
if (!posts.ok) {
throw new Error(posts.attempts.at(-1)?.error?.message || "Graph request failed")
}
console.log(posts.data?.data || [])Session Discovery
Use discoverFacebookBusinessSession when you want to validate a cookie before
calling Graph endpoints.
import { discoverFacebookBusinessSession } from "facebook-business"
const session = await discoverFacebookBusinessSession({
cookie: process.env.FB_BUSINESS_COOKIE || "",
})
console.log({
userId: session.userId,
hasFbDtsg: Boolean(session.fbDtsg),
hasLsd: Boolean(session.lsd),
accessTokenCount: session.accessTokens.length,
})Do not log session.cookie or session.accessTokens in production.
Groups
Read group metadata:
const group = await facebook.getGroupInfo({
groupId: "123456789",
fields: "id,name,privacy,member_count",
})Read recent group posts:
const feed = await facebook.getGroupPosts({
groupId: "123456789",
limit: 25,
hoursBack: 72,
})Create a text post:
const created = await facebook.createGroupPost({
groupId: "123456789",
message: "Server-side post from an approved workflow.",
attachmentType: "none",
})Create a post with image URLs:
const created = await facebook.createGroupPost({
groupId: "123456789",
message: "Post with attached images.",
imageUrls: [
"https://example.com/image-a.jpg",
"https://example.com/image-b.jpg",
],
groupImageFallback: "link",
})Upload a video to a group:
const video = await facebook.createGroupVideoPost({
groupId: "123456789",
videoUrl: "https://example.com/video.mp4",
title: "Product demo",
description: "Uploaded from a backend workflow.",
})Comments and Reactions
Read comments:
const comments = await facebook.getPostComments({
postId: "123456789_987654321",
limit: 20,
})Create a comment:
const comment = await facebook.createComment({
postId: "123456789_987654321",
message: "Thanks for sharing.",
})React to a group post:
const reaction = await facebook.setGroupPostReaction({
postId: "123456789_987654321",
reaction: "LIKE",
reactionLikeState: true,
})Remove a reaction:
await facebook.setGroupPostReaction({
postId: "123456789_987654321",
reactionLikeState: false,
})Pages
Sync managed pages:
const pages = await facebook.syncManagedPages({
fields: "id,name,category,access_token,tasks",
limit: 25,
})Get a page access token:
const pageAccessToken = await facebook.getPageToken({
pageId: "123456789",
})Read page info:
const page = await facebook.getPageInfo({
pageId: "123456789",
accessToken: pageAccessToken || undefined,
fields: "id,name,category",
})Read page posts:
const pagePosts = await facebook.getPagePosts({
pageId: "123456789",
accessToken: pageAccessToken || undefined,
limit: 10,
hoursBack: 72,
})Create a page post:
const pagePost = await facebook.createPagePost({
pageId: "123456789",
accessToken: pageAccessToken || undefined,
message: "Published from a server-side workflow.",
attachmentType: "none",
})React to a page post:
const reaction = await facebook.setPagePostReaction({
postId: "123456789_987654321",
accessToken: pageAccessToken || undefined,
reaction: "LOVE",
reactionLikeState: true,
})Media
Upload one photo from a URL:
const upload = await facebook.uploadPhotoFromUrl({
targetId: "123456789",
imageUrl: "https://example.com/image.jpg",
published: false,
})Upload multiple photos and receive their IDs:
const photoIds = await facebook.getPhotoIdsFromUrls({
targetId: "123456789",
imageUrls: [
"https://example.com/image-a.jpg",
"https://example.com/image-b.jpg",
],
published: false,
})Direct Function Usage
Every client method is also exported as a direct function.
import { createFacebookCommentFromCookie } from "facebook-business"
const result = await createFacebookCommentFromCookie({
cookie: process.env.FB_BUSINESS_COOKIE || "",
postId: "123456789_987654321",
message: "Thanks for sharing.",
graphVersion: "v24.0",
})Result Shape
Most Graph helpers return:
interface FacebookCookieGraphResult<TData> {
ok: boolean
usedTokenIndex: number | null
data: TData | null
attempts: Array<{
tokenIndex: number
status: number
ok: boolean
error: FacebookGraphError | null
data?: TData
}>
}The library may try multiple discovered tokens. Check ok before using data,
and inspect the last attempt for the most relevant Graph error.
if (!result.ok) {
const last = result.attempts.at(-1)
throw new Error(last?.error?.message || `Facebook request failed`)
}Security Notes
- Treat Facebook cookies and access tokens as secrets.
- Never send cookies to frontend code.
- Never commit cookies to source control.
- Avoid logging raw Graph responses when they may contain tokens.
- Run this package only in trusted backend environments.
- Rotate the cookie when permissions or account access changes.
Compliance Notes
This package calls Facebook endpoints with credentials supplied by the caller. You are responsible for ensuring that your usage complies with Facebook terms, privacy requirements, rate limits, and the permissions of the account whose cookie is used.
