Build a Simple Blog Application with Contentful and Next.js

Learn how to build a simple blog application using Contentful and Nextjs. Learn how to use Contentful CMS with Next.js. See how Contentful can be easily integrated into your Next.js app, enabling you to access and display content flexibly and dynamically. 

Contentful is a headless CMS, allowing users to manage and deliver their content through APIs rather than building and maintaining a traditional website or application. This makes it easy to integrate Contentful with various frontend frameworks and tools, including Next.js.

Next.js provides several features that can make it easier to work with Contentful. For example, Next.js offers automatic code splitting, which can help improve the performance of your application by only loading the content needed for each page. Next.js also has inbuilt server-side rendering support, making it easier to deliver your content to a wide range of devices and browsers.

In the article, we’ll walk through how to build a simple blog application using Contentful and Next.js.

Table of contents:

  • What is Contentful CMS?
  • How do you use Contentful?
  • Building an app with Contentful and Next.js
    • Creating the Next.js project
    • Creating the content model
    • Retrieving and displaying content
  • Alternatives to Contentful CMS

What is Contentful CMS?

Contentful is a content management system that allows users to manage and store content in a structured way. It is often used to build websites and applications.

Contentful’s primary selling point is its ability to enable users to create and manage content easily without requiring technical expertise. With this CMS, users can create, edit, and manage content using a simple and intuitive web-based interface. They can then deliver that content to any platform or device using APIs. This makes it a popular choice for organizations that must manage and provide a lot of content across multiple channels.

A key feature of Contentful is its flexibility, allowing for significant user customization. With its powerful APIs and webhooks, users can easily integrate Contentful with other systems and tools, such as ecommerce platforms, analytics tools, and more.

Contentful also offers many inbuilt features to help users manage their content effectively. These include the ability to create custom content models, collaborate with team members, and preview content changes before publishing.

How do you use Contentful?

Before using Contentful, you must create an account and set up your first space. Space is a container where you can store, manage, and deliver your content.

Getting started with Contentful is relatively straightforward and can be done through their user-friendly web interface; follow these steps:

  1. Set up an account: Go to the Contentful website and sign up for an account
  2. Create a space: After you have signed up, click on Spaces > Add space in the side menu and then click the Create a space button. Next, give your space a name, select the appropriate environment (e.g., Production or Staging), and then click the Create button
  3. Add content: Click on Content in the top menu. From there, you can create content models, which define the structure of your content, and then start adding entries
  4. Deliver content: You can use the Contentful APIs or one of the many available SDKs (such as the JavaScript SDK) to retrieve your content and display it in your application or website

Building an app with Contentful and Next.js

Contentful comes with a wide range of features and tools that can be useful when building a Next.js application. For example, it includes support for content modeling, media management, versioning, and localization, which can help you create more advanced and sophisticated applications.

To use Contentful with Next.js, you must create a Contentful account and set up your content models. Then, you can use the Contentful APIs to retrieve your content and display it in your Next.js application.

Let’s create a simple blog app to demonstrate the usage of Contentful CMS with Next.js.

Creating the Next.js project

As a first step, you’ll need to create a new Next.js project and install the necessary dependencies. To do this, use the following commands:

> npx create-next-app my-blog-app
> cd my-blog-app
> npm install contentful

Creating the content model

Next, you’ll need to set up your Contentful space and create a content model for your blog posts. To do this, we’ll follow the steps discussed previously.

First, go to the Contentful website and sign up for an account.

Next, click on Spaces > Add space in the side menu and then click the Create a space button:

Creating Contentful Space

Now, give your space a name (we’ll use ”NextExample”), select the appropriate environment (for this demo, we’ll select “master”), and then click on the Create button.

Next, click on Content model in the top menu and click the Design your content model button:

Creating Contentful Content Model

To create your first piece of content, click the Create a content type button.:

Selecting Content Type Contentful

Next, give your content model a name (for this demo, we’ll use “Blog Post”), click the Create button, and then add the fields that you want to include in your content model (e.g., “title,” “body,” and “author”):

Naming Content Model Contentful

Adding Fields Content Model Contentful

Now you can create entries using this model to populate your space with content.

Retrieving and displaying content

Once you’ve set up your Contentful space and created some content, you can use the Contentful JavaScript SDK to retrieve and display your content in your Next.js app.

In your Next.js project, create a utils.js file and add the following code:

// src/utils.js
import { createClient } from 'contentful';

const client = createClient({
  space: 'YOUR_SPACE_ID',
  accessToken: 'YOUR_ACCESS_TOKEN',
});

// Retrieve the list of blog posts from Contentful
const getBlogPosts = async () => {
  const response = await client.getEntries({
    content_type: 'blogPost',
  });

  return response.items;
};

export default getBlogPosts;

This code uses the Contentful JavaScript SDK to create a client instance and retrieves a list of blog post entries from your Contentful space.

You can then use the getBlogPosts() function to display your blog posts in your Next.js app. For example, you could add the following code to the index.js file in your pages directory to display a list of your blog posts on your app’s homepage:

import styles from "../styles/Home.module.css";
import getBlogPosts from "../src/utils";

export default function Home({ posts }) {
  return (
    <div className={styles.main}>
      <ul className={styles.blogPosts}>
        {posts.map((post) => (
          <li key={post.sys.id}>
            <h2>{post.fields.title}</h2>
            <p>~ by {post.fields.authorName}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

Home.getInitialProps = async () => {
  const posts = await getBlogPosts();

  return { posts };
};

The createClient() function requires the space ID and your access token from the Contentful dashboard.

To get the space ID, navigate to Settings > General settings:

Contentful CMS General Settings

To copy the space ID, click on the copy icon:

Finding Space ID Contentful

To get your access token, navigate to Settings > API keys:

API Access Token Contentful CMS

Next, click the Add API key button to generate a new token:

Generate New API Key Token Contentful

In the next screen, copy the access token from the Content Delivery API – access token field:

Retrieve Access Token Contentful CMS

You can view the the complete code for this example on GitHub; check out the final results below:

Output Next.js App Contentful

Alternatives to Contentful CMS

There are several alternatives to Contentful that you might consider, depending on your specific needs and requirements. Some popular options include:

  • Sanity is a headless CMS that offers a real-time, collaborative editing environment and a robust set of APIs
  • Strapi is an open source headless CMS that offers a user-friendly interface and a wide range of customizable features
  • Kontent.ai is a cloud-based headless CMS that offers advanced features for managing and delivering content across different channels and devices
  • DatoCMS is a headless CMS that allows developers to create and manage content for their websites and applications. It is a popular choice for eCommerce websites because it provides a flexible and scalable way to build and manage online stores
  • Payload is a headless CMS and application framework. It is designed to provide a robust backend for managing and storing content while staying out of the way as applications become more complex

Each of these alternatives has unique features and capabilities, so it’s worth considering them carefully to determine which is best for your project.

Conclusion

Using a CMS like Contentful can improve the performance of your Next.js application because it allows you to store and deliver content separately from your application code. This can make your application faster and more scalable, especially if you have a lot of content or traffic.

With Contentful, you can deliver your content to any platform or device using APIs. Contentful can be integrated into your Next.js web application with just a few lines of code, enabling you to access and display your content flexibly and dynamically.

Original article source at https://blog.logrocket.com

#nextjs 

What is GEEK

Buddha Community

Build a Simple Blog Application with Contentful and Next.js

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Eva  Murphy

Eva Murphy

1625674200

Google analytics Setup with Next JS, React JS using Router Events - 14

In this video, we are going to implement Google Analytics to our Next JS application. Tracking page views of an application is very important.

Google analytics will allow us to track analytics information.

Frontend: https://github.com/amitavroy/video-reviews
API: https://github.com/amitavdevzone/video-review-api
App link: https://video-reviews.vercel.app

You can find me on:
Twitter: https://twitter.com/amitavroy7​
Discord: https://discord.gg/Em4nuvQk

#next js #js #react js #react #next #google analytics

Benefits of Angular JS based Applications

AngularJS was introduced in the year 2009, by Google. AngularJS is a software framework used worldwide by developers. The entire base of this framework is open source. AngularJS has gained popularity among developers because of how it has become for them to create web applications. AngularJS helps in building apps that require less work and reduces the use of unnecessary codes. AngularJS application development is a javascript framework. AngularJS has a clear goal to make the entire process simpler, it also helps app development process and operations as much as it could. AngularJS is used for building applications that support MVC (model view controller) and SPAs (single page web apps) coding and programming structures. AngularJS has been used by some of the top companies in the world to simplify their app development process, like, Google, Paypal, Udemy, mobile site in iPad for HBO, etc. To read more click on the link.

#hire angular js developer #hire dedicated angular js developer #angular js application development #hire dedicated angular js team #hire best angular js application developer

Node JS Development Company| Node JS Web Developers-SISGAIN

Top organizations and start-ups hire Node.js developers from SISGAIN for their strategic software development projects in Illinois, USA. On the off chance that you are searching for a first rate innovation to assemble a constant Node.js web application development or a module, Node.js applications are the most appropriate alternative to pick. As Leading Node.js development company, we leverage our profound information on its segments and convey solutions that bring noteworthy business results. For more information email us at hello@sisgain.com

#node.js development services #hire node.js developers #node.js web application development #node.js development company #node js application

Eva  Murphy

Eva Murphy

1625751960

Laravel API and React Next JS frontend development - 28

In this video, I wanted to touch upon the functionality of adding Chapters inside a Course. The idea was to not think much and start the development and pick up things as they come.

There are places where I get stuck and trying to find answers to it up doing what every developer does - Google and get help. I hope this will help you understand the flow and also how developers debug while doing development.

App url: https://video-reviews.vercel.app
Github code links below:
Next JS App: https://github.com/amitavroy/video-reviews
Laravel API: https://github.com/amitavdevzone/video-review-api

You can find me on:
Twitter: https://twitter.com/amitavroy7​
Discord: https://discord.gg/Em4nuvQk

#next js #api #react next js #next #frontend #development