Théo Blochet

Using Obsidian as local editor for my blog

I use obsidian as Content Management system for this Next.js blog. It's fairly simple:

  • I use Obsidian properties : a date and a title property, which will then automatically be included as frontmatter in the resulting .md file.
  • I have a bash script which I can run to operate the sync between my local obsidian directory, and my local next.js blog repository. That script (included below)
    • Imports all markdown files from my Obsidian vault into the right local Next.js folder.
    • Imports all images from Obsidian into the right folder on Next.js (public/images)
    • Replace spaces by hyphens in file names (plays nicer with Next.js)
# Source directory containing my Obsidian vault for the blog

SRC_DIR="/Users/theoblochet/Coding/writing/public"

  

# Destination directories: posts for markdown, media for images

POSTS_DIR="/Users/theoblochet/Coding/personal/posts"

MEDIA_DIR="/Users/theoblochet/Coding/personal/public/images"

  

# Ensure the destination directories exist

mkdir -p "$POSTS_DIR"

mkdir -p "$MEDIA_DIR"

  

# Copy markdown files to /posts, replacing spaces with hyphens in filenames

find "$SRC_DIR" -type f -name "*.md" -print0 | while IFS= read -r -d $'\0' file; do

new_filename=$(basename "$file" | tr ' ' '-')

cp "$file" "$POSTS_DIR/$new_filename"

done

  

# Copy non-markdown files to /media, excluding config files (.json and .obsidian), replacing spaces with hyphens in filenames

find "$SRC_DIR" -type f ! -name "*.md" ! -name "*.json" ! -name ".obsidian*" -print0 | while IFS= read -r -d $'\0' file; do

new_filename=$(basename "$file" | tr ' ' '-')

cp "$file" "$MEDIA_DIR/$new_filename"

done

Finally, I have two custom changes to my next.js code to parse the markdown files: first, I ensure that the dates in the frontmatter are turned into strings (for some reason next.js can't manipulate date objects for posts):

// Check if the date is a Date object and convert it to string if necessary

if (matterResult.data.date instanceof Date) {

matterResult.data.date = matterResult.data.date.toISOString();

};

I also rewrite the path of all images to point to /images/ (a subdirectory of the public folder, from which Next.js serves static assets), instead of Obsidian's default (images hosted in the same folder as the md file.) I use a simple Regex in the function that serves my markdown content to the blog:

// Replace image filepaths to point to the /images folder instead of current folder

const fileContents = fs.readFileSync(fullPath, "utf8").replace(/(!\[.*?\])\(([^/)]+)\)/g, '$1(/images/$2)');