Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
rayanirban committed Feb 9, 2022
0 parents commit 263ed00
Show file tree
Hide file tree
Showing 70 changed files with 6,007 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
BLOG_INDEX_ID=
NOTION_TOKEN=
31 changes: 31 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
.env.local*

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

.blog_index_data
.blog_index_data_previews

.now
.vercel
5 changes: 5 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"singleQuote": true,
"semi": false,
"trailingComma": "es5"
}
Binary file added assets/table-view.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 19 additions & 0 deletions license
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
14 changes: 14 additions & 0 deletions lint-staged.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const escape = require('shell-quote').quote
const isWin = process.platform === 'win32'

module.exports = {
'**/*.{js,jsx,ts,tsx,json,md,mdx,css,html,yml,yaml,scss,sass}': filenames => {
const escapedFileNames = filenames
.map(filename => `"${isWin ? filename : escape([filename])}"`)
.join(' ')
return [
`prettier --ignore-path='.gitignore' --write ${escapedFileNames}`,
`git add ${escapedFileNames}`,
]
},
}
6 changes: 6 additions & 0 deletions next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/types/global" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
60 changes: 60 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
const fs = require('fs')
const path = require('path')
const {
NOTION_TOKEN,
BLOG_INDEX_ID,
} = require('./src/lib/notion/server-constants')

try {
fs.unlinkSync(path.resolve('.blog_index_data'))
} catch (_) {
/* non fatal */
}
try {
fs.unlinkSync(path.resolve('.blog_index_data_previews'))
} catch (_) {
/* non fatal */
}

const warnOrError =
process.env.NODE_ENV !== 'production'
? console.warn
: (msg) => {
throw new Error(msg)
}

if (!NOTION_TOKEN) {
// We aren't able to build or serve images from Notion without the
// NOTION_TOKEN being populated
warnOrError(
`\nNOTION_TOKEN is missing from env, this will result in an error\n` +
`Make sure to provide one before starting Next.js`
)
}

if (!BLOG_INDEX_ID) {
// We aren't able to build or serve images from Notion without the
// NOTION_TOKEN being populated
warnOrError(
`\nBLOG_INDEX_ID is missing from env, this will result in an error\n` +
`Make sure to provide one before starting Next.js`
)
}

module.exports = {
webpack(cfg, { dev, isServer }) {
// only compile build-rss in production server build
if (dev || !isServer) return cfg

// we're in build mode so enable shared caching for Notion data
process.env.USE_CACHE = 'true'

const originalEntry = cfg.entry
cfg.entry = async () => {
const entries = { ...(await originalEntry()) }
entries['build-rss.js'] = './src/lib/build-rss.ts'
return entries
}
return cfg
},
}
32 changes: 32 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "notion-blog",
"version": "0.1.0",
"scripts": {
"dev": "next dev",
"start": "next start",
"build": "next build && node .next/server/build-rss.js",
"format": "prettier --write \"**/*.{js,jsx,json,ts,tsx,md,mdx,css,html,yml,yaml,scss,sass}\" --ignore-path .gitignore",
"lint-staged": "lint-staged"
},
"pre-commit": "lint-staged",
"dependencies": {
"@zeit/react-jsx-parser": "2.0.0",
"async-sema": "3.1.0",
"github-slugger": "1.2.1",
"katex": "0.12.0",
"next": "^11.1.2",
"prismjs": "1.17.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"uuid": "8.1.0"
},
"devDependencies": {
"@types/katex": "0.11.0",
"@types/node": "14.14.31",
"@types/react": "17.0.2",
"lint-staged": "10.5.4",
"pre-commit": "1.2.2",
"prettier": "2.2.1",
"typescript": "^4.4.4"
}
}
Binary file added public/avatar.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/favicon.ico
Binary file not shown.
Binary file added public/notion.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/og-image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/vercel-and-notion.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
85 changes: 85 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Notion Blog

This is an example Next.js project that shows Next.js' upcoming SSG (static-site generation) support using Notion's **private** API for a backend.

**Note**: This example uses the experimental SSG hooks only available in the Next.js canary branch! The APIs used within this example will change over time. Since it is using a private API and experimental features, use at your own risk as these things could change at any moment.

**Live Example hosted on Vercel**: https://notion-blog.vercel.app/

## Getting Started

To view the steps to setup Notion to work with this example view the post at https://notion-blog.vercel.app/blog/my-first-post or follow the steps below.

## Deploy Your Own

Deploy your own Notion blog with Vercel.

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/ijjk/notion-blog/tree/main&project-name=notion-blog&repository-name=notion-blog)

or

1. Clone this repo `git clone https://github.com/ijjk/notion-blog.git`
2. Configure project with [`vc`](https://vercel.com/download)
3. Add your `NOTION_TOKEN` and `BLOG_INDEX_ID` as environment variables in [your project](https://vercel.com/docs/integrations?query=envir#project-level-apis/project-based-environment-variables). See [here](#getting-blog-index-and-token) for how to find these values
4. Do final deployment with `vc`

Note: if redeploying with `vc` locally and you haven't made any changes to the application's source and only edited in Notion you will need use `vc -f` to bypass build de-duping

## Creating Your Pages Table

**Note**: this is auto run if a table isn't detected the first time visiting `/blog`

### Using the Pre-Configured Script

1. Create a blank page in Notion
2. Clone this repo `git clone https://github.com/ijjk/notion-blog.git`
3. Install dependencies `cd notion-blog && yarn`
4. Run script to create table `NOTION_TOKEN='token' BLOG_INDEX_ID='new-page-id' node scripts/create-table.js` See [here](#getting-blog-index-and-token) for finding the id for the new page

### Manually Creating the Table

1. Create a blank page in Notion
2. Create a **inline** table on that page, don't use a full page table as it requires querying differently
3. Add the below fields to the table

The table should have the following properties:

- `Page`: this the blog post's page
- `Slug`: this is the blog post's slug relative to `/blog`, it should be a text property
- `Published`: this filters blog posts in **production**, it should be a checkbox property
- `Date`: this is when the blog post appears as posted, it should be a date property
- `Authors`: this is a list of Notion users that wrote the post, it should be a person property

![Example Blog Posts Table](./assets/table-view.png)

## Getting Blog Index and Token

To get your blog index value, open Notion and Navigate to the Notion page with the table you created above. While on this page you should be able to get the page id from either:

- the URL, if the URL of your page is https://www.notion.so/Blog-S5qv1QbUzM1wxm3H3SZRQkupi7XjXTul then your `BLOG_INDEX_ID` is `S5qv1QbU-zM1w-xm3H-3SZR-Qkupi7XjXTul`
- the `loadPageChunk` request, if you open your developer console and go to the network tab then reload the page you should see a request for `loadPageChunk` and in the request payload you should see a `pageId` and that is your `BLOG_INDEX_ID`

To get your Notion token, open Notion and look for the `token_v2` cookie.

## Creating Blog Posts

1. In Notion click new on the table to add a new row
2. Fill in the Page name, slug, Date, and Authors
3. At the top of the content area add the content you want to show as a preview (keep this under 2 paragraphs)
4. Add a divider block under your preview content
5. Add the rest of your content under the divider block

## Running Locally

To run the project locally you need to follow steps 1 and 2 of [deploying](#deploy-your-own) and then follow the below steps

1. Install dependencies `yarn`
2. Expose `NOTION_TOKEN` and `BLOG_INDEX_ID` in your environment `export NOTION_TOKEN='<your-token>'`and `export BLOG_INDEX_ID='<your-blog-index-id>'` or `set NOTION_TOKEN="<your-token>" && set BLOG_INDEX_ID="<your-blog-index-id>"` for Windows
3. Run next in development mode `yarn dev`
4. Build and run in production mode `yarn build && yarn start`

## Credits

- Guillermo Rauch [@rauchg](https://twitter.com/rauchg) for the initial idea
- Shu Ding [@shuding\_](https://twitter.com/shuding_) for the design help
- Luis Alvarez [@luis_fades](https://twitter.com/luis_fades) for design help and bug catching
3 changes: 3 additions & 0 deletions scripts/create-table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const main = require('../src/lib/notion/createTable')

main()
38 changes: 38 additions & 0 deletions src/components/code.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import Prism from 'prismjs'
import 'prismjs/components/prism-jsx'

const Code = ({ children, language = 'javascript' }) => {
return (
<>
<pre>
<code
dangerouslySetInnerHTML={{
__html: Prism.highlight(
children,
Prism.languages[language.toLowerCase()] ||
Prism.languages.javascript
),
}}
/>
</pre>

<style jsx>{`
pre {
tab-size: 2;
}
code {
overflow: auto;
display: block;
padding: 0.8rem;
line-height: 1.5;
background: #f5f5f5;
font-size: 0.75rem;
border-radius: var(--radius);
}
`}</style>
</>
)
}

export default Code
15 changes: 15 additions & 0 deletions src/components/counter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React, { useState } from 'react'

const Counter = ({ initialValue }) => {
const [clicks, setClicks] = useState(initialValue)

return (
<div style={{ margin: '10px 0 20px' }}>
<p>Count: {clicks}</p>
<button onClick={() => setClicks(clicks + 1)}>increase count</button>
<button onClick={() => setClicks(clicks - 1)}>decrease count</button>
</div>
)
}

export default Counter
16 changes: 16 additions & 0 deletions src/components/dynamic.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import dynamic from 'next/dynamic'
import ExtLink from './ext-link'

export default {
// default tags
ol: 'ol',
ul: 'ul',
li: 'li',
p: 'p',
blockquote: 'blockquote',
a: ExtLink,

Code: dynamic(() => import('./code')),
Counter: dynamic(() => import('./counter')),
Equation: dynamic(() => import('./equation')),
}
28 changes: 28 additions & 0 deletions src/components/equation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { renderToString, ParseError } from 'katex'

function render(expression: string, displayMode: boolean): string {
let result: string
try {
result = renderToString(expression, { displayMode: displayMode })
} catch (e) {
if (e instanceof ParseError) {
result = e.message
}
if (process.env.NODE_ENV !== 'production') {
console.error(e)
}
}
return result
}

const Equation = ({ children, displayMode = true }) => {
return (
<span
dangerouslySetInnerHTML={{
__html: render(children, displayMode),
}}
/>
)
}

export default Equation
4 changes: 4 additions & 0 deletions src/components/ext-link.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const ExtLink = (props) => (
<a {...props} rel="noopener" target={props.target || '_blank'} />
)
export default ExtLink
Loading

0 comments on commit 263ed00

Please sign in to comment.