Next.js - How to Get Session Information in Server Side vs Client Side iusing Next-auth
Introduction Next-auth is a fantastic library for abstracting handling of…
May 04, 2021
In this post, we will integrate Next.js with Strapi fully. And we will create a class which will call REST APIs to our backend.
We will also see a sample index.jsx
file to fetch all articles.
And, we will start building from these building blocks.
So far, we have seen:
Since we will be calling REST APIs in almost every page. It is better to write a common code which will wrap our logic of calling APIs and JWT tokens.
Lets write an /components/api/api_client.js
import { getSession } from 'next-auth/client'
import axios from 'axios'
class ApiClient {
async getAuthHeader () {
let header = {}
const session = await getSession();
if (session.jwt) {
header = {Authorization: `Bearer ${session.jwt}`};
}
return header;
}
async saveArticle(args) {
console.log('Saving Article', args);
const headers = await this.getAuthHeader();
try {
let { data } = await axios.post(
`${process.env.NEXT_PUBLIC_API_URL}/articles`,
{
title: args.title,
body: args.body
},
{
headers: headers,
}
)
return data;
} catch (e) {
return e;
}
}
async updateArticle(args) {
console.log('Updating Article', args);
const headers = await this.getAuthHeader();
try {
let { data } = await axios.put(
`${process.env.NEXT_PUBLIC_API_URL}/articles/${args.id}`,
{
title: args.title,
body: args.body
},
{
headers: headers,
}
)
return data;
} catch (e) {
return e;
}
}
async getArticleById(id) {
try {
let { data } = await axios.get(
`${process.env.NEXT_PUBLIC_API_URL}/articles/${id}`
)
return data;
} catch (e) {
return e;
}
}
async getArticleBySlug(slug) {
let {data } = await axios.get(
`${process.env.NEXT_PUBLIC_API_URL}/articles?slug=${slug}`
);
return data;
}
async getArticles() {
let {data } = await axios.get(
`${process.env.NEXT_PUBLIC_API_URL}/articles`
);
return data;
}
async uploadInlineImageForArticle(file) {
const headers = await this.getAuthHeader();
const formData = new FormData();
formData.append('files', file);
try {
let { data } = await axios.post(
`${process.env.NEXT_PUBLIC_API_URL}/upload`,
formData,
{
headers: headers,
}
)
return data;
} catch (e) {
console.log('caught error');
console.error(e);
return null;
}
}
}
module.exports = new ApiClient();
We have wrapped all api code in a class. Now, who so ever need to call rest apis, can use this class.
import Head from 'next/head'
import SimpleLayout from '../components/layout/simple'
import apiClient from '../components/api/api_client'
export default function Home(initialData) {
return (
<SimpleLayout>
<section className="jumbotron text-center">
<div className="container">
<h1>Subscribe to GyanBlog</h1>
<p className="lead text-muted">
Learn and Share
</p>
</div>
</section>
<div className="row">
<div>
{initialData.articles && initialData.articles.map((each, index) => {
return(
<div key={index}>
<h3>{each.title}</h3>
<p>{each.body}</p>
</div>
)
})}
</div>
</div>
</SimpleLayout>
)
}
export async function getServerSideProps({req}) {
try {
let articles = await apiClient.getArticles();
console.log(articles);
return {props: {articles: articles}};
} catch (e) {
console.log('caught error');
return {props: {articles: []}};
}
}
The code is simple to use.
The function getServerSideProps
is a special method by Next.js and is executed the first thing in this file index.jsx
. And, we are fetching all articles here, and returning the data.
Now, this data will be received by our index.jsx
react component. Here, we have used a function component. It will receive the data as props
, and you can use it in the way you want.
Introduction Next-auth is a fantastic library for abstracting handling of…
Introduction This post is in contuation of our previous post: How to use Draft…
Introduction I was trying to upload images to my backend using rest APIs. I was…
Introduction We have a page, for example a . And, upon submission we would want…
Introduction In this post we will see: How to prepare a docker image for your…
Introduction In this step-by-step tutorial, we will setup strapi headless CMS…
Introduction In this post we will see following: How to schedule a job on cron…
Introduction There are some cases, where I need another git repository while…
Introduction In this post, we will see how to fetch multiple credentials and…
Introduction I have an automation script, that I want to run on different…
Introduction I had to write a CICD system for one of our project. I had to…
Introduction Java log4j has many ways to initialize and append the desired…