Lens Protocol: Build a Decentralized Social Media Network Stored on IPFS

Jessie Mongeon
12 min readFeb 9, 2023

This guide was originally published on https://docs.filebase.com. Check out the Filebase documentation site for the latest Web3 tutorials using IPFS through Filebase.

Learn how to build a decentralized social media network stored on IPFS.

What is Lens Protocol?

Lens Protocol is a smart contract based social network protocol using the Polygon blockchain network that enables developers to build decentralized social media websites that use smart contracts for each transaction on the website.

Read below to learn how to build a decentralized social media network stored on IPFS.

Prerequisites:

  • Install Node.js and npm.
  • Download and install an IDE of your choice, such as VSCode.
  • Sign up for a free Filebase account.
  • Have your Filebase Access and Secret Keys. Learn how to view your access keys here.
  • Create a Filebase IPFS Bucket. Learn how to create a bucket here.

1. First, we need a Filebase IPFS bucket.

To do this, navigate to console.filebase.com. If you don’t have an account already, sign up, then log in.

2. Select ‘Buckets’ from the left side bar menu, or navigate to console.filebase.com/buckets.

Select ‘Create Bucket’ in the top right corner to create a new bucket.

3. Enter a bucket name and choose the IPFS storage network to create the bucket.

Bucket names must be unique across all Filebase users, be between 3 and 63 characters long, and can contain only lowercase characters, numbers, and dashes.

4. Next, download and install S3FS-FUSE on a Linux or macOS system.

5. Open a terminal window. Then, set up an Access Key file for use with S3FS-FUSE.

Set up a credentials file for S3FS at ${HOME}/.passwd-s3fs. You will need to save your Filebase Access and Secret keys to this file and give it owner permissions. You can do so with the following commands:

echo ACCESS_KEY_ID:SECRET_ACCESS_KEY > ${HOME}/.passwd-s3fs

chmod 600 ${HOME}/.passwd-s3fs

ACCESS_KEY_ID is your Filebase Access key, and SECRET_ACCESS_KEY is your Filebase Secret key. For more information on Filebase access keys, see here.

6. Mount your bucket.

You can mount a Filebase IPFS bucket with the command:

s3fs mybucket /path/to/mountpoint -o passwd_file=${HOME}/.passwd-s3fs -o url=https://s3.filebase.com

  • mybucket: name of your Filebase bucket
  • /path/to/mountpoint

7. Now, navigate into the mounted Filebase bucket.

cd /path/to/mounted/bucket

8. Create a new folder for your project, then navigate inside that folder:

mkdir decentralized-social-media

9. Clone the GitHub repository for this project:

git clone –branch starter https://github.com/Olanetsoft/decentralize-social-media-app-with-lens-protocol.git decentralized-social-media

cd decentralized-social-media

10. Install and start the app with the command:

npm install && npm run build && npm start

11. Navigate to localhost:3000. You will see the default app screen:

By default, this app shows only one profile that is pre-configured. We’ll need to edit the API to fetch all profiles currently built using the Lens protocol.

12. Open the pages/api/api.js file and replace the existing code with the following:

import { createClient } from "urql";

const API_URL = "<https://api.lens.dev>";

// Setup the client to use the API_URL as the base URL
export const client = createClient({
url: API_URL,
});

// Get the recommended profiles
export const getProfiles = `
query RecommendedProfiles {
recommendedProfiles {
id
name
bio
attributes {
displayType
traitType
key
value
}
followNftAddress
metadata
isDefault
picture {
... on NftImage {
contractAddress
tokenId
uri
verified
}
... on MediaSet {
original {
url
mimeType
}
}
__typename
}
handle
coverPicture {
... on NftImage {
contractAddress
tokenId
uri
verified
}
... on MediaSet {
original {
url
mimeType
}
}
__typename
}
ownedBy
dispatcher {
address
canUseRelay
}
stats {
totalFollowers
totalFollowing
totalPosts
totalComments
totalMirrors
totalPublications
totalCollects
}
followModule {
... on FeeFollowModuleSettings {
type
amount {
asset {
symbol
name
decimals
address
}
value
}
recipient
}
... on ProfileFollowModuleSettings {
type
}
... on RevertFollowModuleSettings {
type
}
}
}
}
`;

This piece of code imports the createClient module from urql that is used to send GraphQL requests to the project’s API, then it sets up a client to make a request to the Lens protocol API. Finally, it sets up the getProfiles endpoint to retrieve current Lens Protocol profiles.

13. Next, open the index.js file and replace the existing content with the following code:

import Head from "next/head";
import Profiles from "../components/profiles";

import { useState, useEffect } from "react";

import { client, getProfiles } from "../pages/api/api";

export default function Home() {

// Setup the state for the profiles
const [profiles, setProfiles] = useState([]);

// Get the recommended profiles
const fetchProfiles = async () => {
try {
const response = await client.query(getProfiles).toPromise();

setProfiles(response.data.recommendedProfiles);

console.log(response.data.recommendedProfiles);
} catch (e) {
console.log(e);
}
};

// Run the fetchProfiles function when the component is mounted
useEffect(() => {
fetchProfiles();
}, []);

// Render the component
return (
<div className="grid grid-cols-3 divide-x">
<Head>
<title>Decentralize Social Media App - Lens protocol</title>
<meta name="description" content="Decentralize Social Media App" />
<link rel="icon" href="/favicon.ico" />
</Head>
<div className="col-span-3">
<div className="px-4 py-8">
<h1 className="text-3xl font-bold leading-tight text-center">
Decentralize Social Media App - Lens protocol
</h1>
<p className="text-center">
This is a decentralized social media app built on the Lens protocol.
</p>
</div>
</div>
{profiles && profiles.length > 0 ? (
<Profiles profiles={profiles} />
) : (
<div className="text-center text-gray-500 p-5 font-medium text-xl tracking-tight leading-tight">
<p>Loading...</p>
</div>
)}
</div>
);
}

This code creates the variable profiles that is used to save retrieved profile data, then validates a profile’s value after the fetchProfile function is returned.

14. Navigate into the components directory, then open the profiles.js file. Update the file’s content with the following code:

import React from "react";
import Image from "next/image";
import Link from "next/link";

export default function Profiles({ profiles }) {
return (
<>
{profiles.length > 0 &&
profiles.map((profile, index) => (
<Link href={`/profile/${profile.id}`} key={index}>
<div className="max-w-md rounded-lg shadow-lg bg-white mt-5 mb-5 p-5 border border-radius-8 cursor-pointer hover:bg-gray-100 hover:shadow-lg ml-8">
<div className="flex flex-shrink-0 p-4 pb-0">
<div className="flex items-center">
<div>
{profile &&
profile.picture &&
profile.picture.original &&
profile.picture.original.url ? (
<Image
src={`${profile.picture.original.url}`}
alt={profile.name}
width={64}
height={64}
className="rounded-full"
/>
) : (
<div className="rounded-full bg-gray-500 h-12 w-12"></div>
)}
</div>
<div className="ml-3">
<p className="text-base leading-6 font-medium ">
{profile.name}{" "}
<span className="text-sm leading-5 font-medium text-gray-500 group-hover:text-gray-400 transition ease-in-out duration-150">
@{profile.handle}
</span>
</p>
</div>
</div>
</div>
<div className="pl-16">
<p className="text-base width-auto font-small flex-shrink">
{profile.bio ? profile.bio : "No bio available 😢"}
</p>
</div>
</div>
</Link>
))}
</>
);
}

15. Open the next.config.js file and replace the content with the following:

/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
images: {
domains: [
"pbs.twimg.com",
"ipfs.filebase.io",
"ipfs.infura.io",
"lens.infura-ipfs.io",
"statics-polygon-lens-staging.s3.eu-west-1.amazonaws.com",
"s3-us-west-2.amazonaws.com",
],
},
};

module.exports = nextConfig;

16. Save all changes. Then, start the app in development mode using the command:

yarn dev

You will now see the following screen at localhost:3000:

17. If you click on a single profile, you will get an error 404 page, so let’s fix that. Open the pages/api/api.js code and add the following code:

//...

export const getProfile = `
query Profiles($id: ProfileId!) {
profiles(request: { profileIds: [$id], limit: 25 }) {
items {
id
name
bio
attributes {
displayType
traitType
key
value
}
metadata
isDefault
picture {
... on NftImage {
contractAddress
tokenId
uri
verified
}
... on MediaSet {
original {
url
mimeType
}
}
__typename
}
handle
coverPicture {
... on NftImage {
contractAddress
tokenId
uri
verified
}
... on MediaSet {
original {
url
mimeType
}
}
__typename
}
ownedBy
dispatcher {
address
canUseRelay
}
stats {
totalFollowers
totalFollowing
totalPosts
totalComments
totalMirrors
totalPublications
totalCollects
}
}
pageInfo {
prev
next
totalCount
}
}
}
`;

18. Then, open the pages/profiles/[id].js file and insert the following:

</div>

<div className=”text-lg tracking-tight font-bold hover:text-teal”>

{profile && profile.stats.totalFollowing}

</div>

</li>

<li className=”text-center py-3 px-4 border-b-2 border-solid border-transparent hover:border-teal”>

<div className=”text-sm font-bold tracking-tight mb-1">

Followers

</div>

<div className=”text-lg tracking-tight font-bold hover:text-teal”>

{profile && profile.stats.totalFollowers}

</div>

</li>

<li className=”text-center py-3 px-4 border-b-2 border-solid border-transparent hover:border-teal”>

<div className=”text-sm font-bold tracking-tight mb-1">

Comments

</div>

<div className=”text-lg tracking-tight font-bold hover:text-teal”>

{profile && profile.stats.totalComments}

</div>

</li>

<li className=”text-center py-3 px-4 border-b-2 border-solid border-transparent hover:border-teal”>

<div className=”text-sm font-bold tracking-tight mb-1">

Collection

</div>

<div className=”text-lg tracking-tight font-bold hover:text-teal”>

{profile && profile.stats.totalCollects}

</div>

</li>

</ul>

</div>

</div>

</div>

<div className=”container mx-auto flex flex-col lg:flex-row mt-3 text-sm leading-normal”>

<div className=”w-full lg:w-1/4 pl-4 lg:pl-0 pr-6 mt-8 mb-4">

<h1>

<a

href=”#”

className=”text-black font-bold no-underline hover:underline”

>

{profile && profile.name}

</a>

</h1>

<div className=”mb-4">@{profile && profile.handle}</div>

<div className=”mb-4">{profile && profile.bio}</div>

<div className=”mb-2">

<i className=”fa fa-link fa-lg text-grey-darker mr-1"></i>

<a href=”#” className=”text-teal no-underline hover:underline”>

lens.dev

</a>

</div>

</div>

<div className=”w-full lg:w-1/2 bg-white mb-4">

<div className=”p-3 text-lg font-bold border-b border-solid border-grey-light”>

Publications

</div>

</div>

<div className=”w-full lg:w-1/4 pl-4">

<div className=”bg-white p-3 mb-3">

<div>

<span className=”text-lg font-bold”>Who to follow</span>

<span>&middot;</span>

</div>

<div className=”flex border-b border-solid border-grey-light”>

<div className=”py-2">

<a href=”#”>

<Image

src=”https://s3-us-west-2.amazonaws.com/s.cdpn.io/195612/tt_follow1.jpg"

alt=”follow1"

className=”rounded-full h-12 w-12"

width={50}

height={50}

/>

</a>

</div>

<div className=”pl-2 py-2 w-full”>

<div className=”flex justify-between mb-1">

<div>

<a href=”#” className=”font-bold text-black”>

I D R I S

</a>{“ “}

<a href=”#” className=”text-grey-dark”>

@olanetsoft.lens

</a>

</div>

<div>

<a href=”#” className=”text-grey hover:text-grey-dark”>

<i className=”fa fa-times”></i>

</a>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

);

}

19. Now, if you click on an individual profile, you’ll see the user’s information:

20. Lastly, let’s add functionality to view the user’s publications. Open the pages/api/api.js file again and add the following code:

//…

export const getPublications = `

query Publications($id: ProfileId!, $limit: LimitScalar) {

publications(request: {

profileId: $id,

publicationTypes: [POST],

limit: $limit

}) {

items {

__typename

… on Post {

…PostFields

}

}

}

}

fragment PostFields on Post {

id

metadata {

…MetadataOutputFields

}

createdAt

}

fragment MetadataOutputFields on MetadataOutput {

name

description

content

media {

original {

…MediaFields

}

}

attributes {

displayType

traitType

value

}

}

fragment MediaFields on Media {

url

mimeType

}

`;

21. Then, replace the content in the [id].js with the following:

import { useState, useEffect } from “react”;

import { useRouter } from “next/router”;

import Link from “next/link”;

import Image from “next/image”;

import { client, getProfile, getPublications } from “../api/api”;

export default function Profile() {

const [profile, setProfile] = useState();

const [publications, setPublications] = useState();

const router = useRouter();

const { id } = router.query;

async function fetchProfile() {

try {

const returnedProfile = await client

.query(getProfile, { id })

.toPromise();

const profileData = returnedProfile.data.profiles.items[0];

setProfile(profileData);

} catch (err) {

console.log(“error fetching profile…”, err);

}

}

async function getProfilePublications() {

try {

const returnedPublications = await client

.query(getPublications, { id, limit: 10 })

.toPromise();

const publicationsData = returnedPublications.data.publications.items;

console.log(“publicationsData”, publicationsData);

setPublications(publicationsData);

} catch (err) {

console.log(“error fetching publications…”, err);

}

}

useEffect(() => {

if (id) {

fetchProfile();

getProfilePublications();

}

}, [id]);

return (

<div>

<div className=”bg-white”>

<div className=”container mx-auto flex flex-col lg:flex-row items-center py-4">

<nav className=”w-full lg:w-2/5">

<Link

href=”/”

className=”text-grey-darker text-sm mr-4 font-semibold pb-6 border-b-2 border-solid border-transparent no-underline hover:text-teal hover:border-teal hover:no-underline”

>

Home

</Link>

</nav>

<div className=”w-full lg:w-1/5 text-center my-4 lg:my-0">

<a href=”#”>

<i className=”fa fa-twitter fa-lg text-blue”></i>

</a>

</div>

<div className=”w-full lg:w-2/5 flex lg:justify-end”>

<div className=”mr-4">

<a href=”#”>

{profile &&

profile.picture &&

profile.picture.original &&

profile.picture.original.url ? (

<Image

src={profile.picture.original.url}

alt=”avatar”

className=”h-8 w-8 rounded-full”

width={50}

height={50}

/>

) : (

<div className=”rounded-full bg-gray-500 h-12 w-12"></div>

)}

</a>

</div>

</div>

</div>

</div>

<div className=”container h-20 mx-auto flex flex-col lg:flex-row items-center justify-center”>

{profile &&

profile.coverPicture &&

profile.coverPicture.original &&

profile.coverPicture.original.url ? (

<Image

src={profile.coverPicture.original.url}

alt=”logo”

className=”rounded-lg h-48 w-48 lg:absolute lg:pin-l lg:pin-t lg:-mt-24"

width={800}

height={100}

/>

) : null}

</div>

<div className=”bg-white shadow mt-4">

<div className=”container mx-auto flex flex-col lg:flex-row items-center lg:relative”>

<div className=”w-full lg:w-1/4">

{profile &&

profile.picture &&

profile.picture.original &&

profile.picture.original.url ? (

<Image

src={profile.picture.original.url}

alt=”logo”

className=”rounded-full h-48 w-48 lg:absolute lg:pin-l lg:pin-t lg:-mt-24"

width={74}

height={74}

/>

) : (

<div className=”rounded-full bg-gray-500 h-12 w-12"></div>

)}

</div>

<div className=”w-full lg:w-1/2">

<ul className=”list-reset flex”>

<li className=”text-center py-3 px-4 border-b-2 border-solid border-transparent border-teal”>

<div className=”text-sm font-bold tracking-tight mb-1">

Publications

</div>

<div className=”text-lg tracking-tight font-bold text-teal”>

{profile && profile.stats.totalPublications}

</div>

</li>

<li className=”text-center py-3 px-4 border-b-2 border-solid border-transparent border-teal”>

<div className=”text-sm font-bold tracking-tight mb-1">

Posts

</div>

<div className=”text-lg tracking-tight font-bold text-teal”>

{profile && profile.stats.totalPosts}

</div>

</li>

<li className=”text-center py-3 px-4 border-b-2 border-solid border-transparent hover:border-teal”>

<div className=”text-sm font-bold tracking-tight mb-1">

Following

</div>

<div className=”text-lg tracking-tight font-bold hover:text-teal”>

{profile && profile.stats.totalFollowing}

</div>

</li>

<li className=”text-center py-3 px-4 border-b-2 border-solid border-transparent hover:border-teal”>

<div className=”text-sm font-bold tracking-tight mb-1">

Followers

</div>

<div className=”text-lg tracking-tight font-bold hover:text-teal”>

{profile && profile.stats.totalFollowers}

</div>

</li>

<li className=”text-center py-3 px-4 border-b-2 border-solid border-transparent hover:border-teal”>

<div className=”text-sm font-bold tracking-tight mb-1">

Comments

</div>

<div className=”text-lg tracking-tight font-bold hover:text-teal”>

{profile && profile.stats.totalComments}

</div>

</li>

<li className=”text-center py-3 px-4 border-b-2 border-solid border-transparent hover:border-teal”>

<div className=”text-sm font-bold tracking-tight mb-1">

Collection

</div>

<div className=”text-lg tracking-tight font-bold hover:text-teal”>

{profile && profile.stats.totalCollects}

</div>

</li>

</ul>

</div>

</div>

</div>

<div className=”container mx-auto flex flex-col lg:flex-row mt-3 text-sm leading-normal”>

<div className=”w-full lg:w-1/4 pl-4 lg:pl-0 pr-6 mt-8 mb-4">

<h1>

<a

href=”#”

className=”text-black font-bold no-underline hover:underline”

>

{profile && profile.name}

</a>

</h1>

<div className=”mb-4">@{profile && profile.handle}</div>

<div className=”mb-4">{profile && profile.bio}</div>

<div className=”mb-2">

<i className=”fa fa-link fa-lg text-grey-darker mr-1"></i>

<a href=”#” className=”text-teal no-underline hover:underline”>

lens.dev

</a>

</div>

</div>

<div className=”w-full lg:w-1/2 bg-white mb-4">

<div className=”p-3 text-lg font-bold border-b border-solid border-grey-light”>

Publications

</div>

{publications &&

publications.map((publication) => (

<div key={publication.id}>

<div className=”flex border-b border-solid border-grey-light”>

<div className=”w-1/8 text-right pl-3 pt-3">

<div>

<i className=”fa fa-thumb-tack text-teal mr-2"></i>

</div>

<div>

<a href=”#”>

{profile &&

profile.picture &&

profile.picture.original &&

profile.picture.original.url ? (

<Image

src={profile.picture.original.url}

alt=”avatar”

className=”rounded-full h-12 w-12 mr-2"

width={50}

height={50}

/>

) : (

<div className=”rounded-full bg-gray-500 h-12 w-12"></div>

)}

</a>

</div>

</div>

<div className=”w-7/8 p-3 pl-0 ml-4">

<div className=”flex justify-between”>

<div>

<span className=”font-bold”>

<a href=”#” className=”text-black”>

{profile && profile.name}

</a>

</span>

<span className=”text-grey-dark”>

@{profile && profile.handle}

</span>

<span className=”text-grey-dark”>&middot;</span>

</div>

</div>

<div className=”mb-4">

<p className=”mb-6 text-grey-dark mt-2">

{publication.metadata.content}

</p>

<p>

<a href=”#”>

{publication.metadata.media > 0 &&

publication.metadata.media[0].original.mimetype ===

“video/mp4” ? (

<video

controls

style={{ width: “700”, height: “400” }}

>

<source

src={publication.metadata.media[0].original.url}

type=”video/mp4"

/>

</video>

) : null}

</a>

</p>

</div>

</div>

</div>

</div>

))}

</div>

<div className=”w-full lg:w-1/4 pl-4">

<div className=”bg-white p-3 mb-3">

<div>

<span className=”text-lg font-bold”>Who to follow</span>

<span>&middot;</span>

</div>

<div className=”flex border-b border-solid border-grey-light”>

<div className=”py-2">

<a href=”#”>

<Image

src=”<https://s3-us-west-2.amazonaws.com/s.cdpn.io/195612/tt_follow1.jpg>"

alt=”follow1"

className=”rounded-full h-12 w-12"

width={50}

height={50}

/>

</a>

</div>

<div className=”pl-2 py-2 w-full”>

<div className=”flex justify-between mb-1">

<div>

<a href=”#” className=”font-bold text-black”>

I D R I S

</a>{“ “}

<a href=”#” className=”text-grey-dark”>

@olanetsoft.lens

</a>

</div>

<div>

<a href=”#” className=”text-grey hover:text-grey-dark”>

<i className=”fa fa-times”></i>

</a>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

);

}

22. Now, you can click on a user’s profile and view their existing publications within their profile:

23. From here, you can style the website using TailwindCSS, or play around with comment and following functionality.

--

--