Skip to content

Commit

Permalink
Improved NextJS base path fetching from environment variables
Browse files Browse the repository at this point in the history
  • Loading branch information
FlorianLeChat committed Aug 6, 2023
1 parent c8945b9 commit 03e7fab
Show file tree
Hide file tree
Showing 16 changed files with 21 additions and 72 deletions.
3 changes: 0 additions & 3 deletions .env
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
# NextJS parameters
NEXT_PUBLIC_ENV=development

# Website public URL
NEXT_PUBLIC_URL=http://localhost:3000/

# Google Analytics and reCAPTCHA keys
NEXT_PUBLIC_RECAPTCHA_ENABLED=false
NEXT_PUBLIC_RECAPTCHA_PUBLIC_KEY=6Lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Expand Down
1 change: 1 addition & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"no-unused-vars": "off",
"linebreak-style": "off",
"space-in-parens": ["error", "always"],
"no-underscore-dangle": ["error", { "allow": ["__NEXT_ROUTER_BASEPATH"] }], // https://github.com/vercel/next.js/issues/52201#issuecomment-1620629437
"object-curly-newline": ["error", { "ObjectExpression": { "consistent": true } }],
"array-bracket-spacing": ["error", "always"],
"template-curly-spacing": ["error", "always"],
Expand Down
12 changes: 4 additions & 8 deletions app/components/cookie-consent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,9 @@

import { run } from "vanilla-cookieconsent";
import { useEffect } from "react";
import { getBasePath } from "@/utilities/NextRouter";

export default function CookieConsent()
{
// Déclaration des constantes.
const basePath = getBasePath();

// Affichage du consentement des cookies.
// Source : https://cookieconsent.orestbida.com/reference/api-reference.html
useEffect( () =>
Expand All @@ -31,7 +27,7 @@ export default function CookieConsent()

// Paramètres internes des cookies.
cookie: {
path: basePath,
path: process.env.__NEXT_ROUTER_BASEPATH,
name: "NEXT_ANALYTICS"
},

Expand Down Expand Up @@ -74,13 +70,13 @@ export default function CookieConsent()
default: "en",
autoDetect: "document",
translations: {
en: `${ basePath }/locales/en.json`,
fr: `${ basePath }/locales/fr.json`
en: `${ process.env.__NEXT_ROUTER_BASEPATH }/locales/en.json`,
fr: `${ process.env.__NEXT_ROUTER_BASEPATH }/locales/fr.json`
}
}
}
);
}, [ basePath ] );
}, [] );

// Affichage du rendu HTML du composant.
return null;
Expand Down
9 changes: 3 additions & 6 deletions app/components/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,15 @@

"use client";

import { useTranslation } from "@/utilities/ClientTranslations";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useState, useEffect, useCallback } from "react";
import { faMoon, faSun, faBars, faTimes, faCookieBite } from "@fortawesome/free-solid-svg-icons";

import { getBasePath } from "@/utilities/NextRouter";
import { useTranslation } from "@/utilities/ClientTranslations";

export default function Header()
{
// Déclaration des constantes.
const { t } = useTranslation();
const basePath = getBasePath();

// Déclaration des variables d'état.
const [ theme, setTheme ] = useState( "light" );
Expand Down Expand Up @@ -47,9 +44,9 @@ export default function Header()
}

// On enregistre enfin le thème cible dans les cookies du navigateur.
document.cookie = `NEXT_THEME=${ target }; path=${ basePath }`;
document.cookie = `NEXT_THEME=${ target }; path=${ process.env.__NEXT_ROUTER_BASEPATH }`;
}
}, [ passed, theme, basePath ] );
}, [ passed, theme ] );

// Affichage ou disparition du menu de navigation.
// Note : ce menu est seulement visible sur les écrans de petite taille.
Expand Down
6 changes: 2 additions & 4 deletions app/components/recaptcha.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
"use client";

import Script from "next/script";
import { getBasePath } from "@/utilities/NextRouter";
import type { CookieValue } from "vanilla-cookieconsent";
import { useState, useEffect, useCallback } from "react";

Expand All @@ -24,7 +23,6 @@ export default function Recaptcha()
}

// Déclaration des constantes.
const basePath = getBasePath();
const recaptchaUrl = new URL( "https://www.google.com/recaptcha/api.js" );
recaptchaUrl.searchParams.append( "render", process.env.NEXT_PUBLIC_RECAPTCHA_PUBLIC_KEY ?? "" );
recaptchaUrl.searchParams.append( "onload", "setupRecaptcha" );
Expand Down Expand Up @@ -56,15 +54,15 @@ export default function Recaptcha()
} );

// On envoie enfin le jeton au serveur pour vérification.
fetch( `${ basePath }/api/recaptcha`, {
fetch( `${ process.env.__NEXT_ROUTER_BASEPATH }/api/recaptcha`, {
body: JSON.stringify( { token } ),
method: "POST",
headers: {
"Content-type": "application/json; charset=UTF-8"
}
} );
} );
}, [ basePath ] );
}, [] );

// Détection des changements de consentement des cookies.
useEffect( () =>
Expand Down
5 changes: 1 addition & 4 deletions app/legacy/admin/login/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@
// Route vers la page de connexion à l'administration de l'ancienne version du site.
//

// Importation des fonctions utilitaires.
import { getBasePath } from "@/utilities/NextRouter";

// Affichage de la page.
export default function Page()
{
Expand All @@ -13,7 +10,7 @@ export default function Page()
<>
{/* Vidéo en arrière-plan */}
<video autoPlay muted loop>
<source src={`${ getBasePath() }/assets/videos/login.mp4`} type="video/mp4" />
<source src={`${ process.env.__NEXT_ROUTER_BASEPATH }/assets/videos/login.mp4`} type="video/mp4" />
</video>

{/* Formulaire de connexion */}
Expand Down
5 changes: 1 addition & 4 deletions app/legacy/admin/logout/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@
// Importation des dépendances.
import Link from "next/link";

// Importation des fonctions utilitaires.
import { getBasePath } from "@/utilities/NextRouter";

// Affichage de la page.
export default function Page()
{
Expand All @@ -16,7 +13,7 @@ export default function Page()
<>
{/* Vidéo en arrière-plan */}
<video autoPlay muted loop>
<source src={`${ getBasePath() }/assets/videos/logout.mp4`} type="video/mp4" />
<source src={`${ process.env.__NEXT_ROUTER_BASEPATH }/assets/videos/logout.mp4`} type="video/mp4" />
</video>

{/* Page de déconnexion */}
Expand Down
5 changes: 1 addition & 4 deletions app/legacy/admin/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@
// Importation de la feuille de style.
import "./page.scss";

// Importation des fonctions utilitaires.
import { getBasePath } from "@/utilities/NextRouter";

// Affichage de la page.
export default function Page()
{
Expand All @@ -16,7 +13,7 @@ export default function Page()
<>
{/* Vidéo en arrière-plan */}
<video autoPlay muted loop>
<source src={`${ getBasePath() }/assets/videos/landing.mp4`} type="video/mp4" />
<source src={`${ process.env.__NEXT_ROUTER_BASEPATH }/assets/videos/landing.mp4`} type="video/mp4" />
</video>

{/* Visualisation et édition des tables */}
Expand Down
5 changes: 1 addition & 4 deletions app/legacy/components/footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,13 @@

import Link from "next/link";
import { lazy, useState } from "react";

import { getBasePath } from "@/utilities/NextRouter";
import { useTranslation } from "@/utilities/ClientTranslations";

const Contributions = lazy( () => import( "./contributions" ) );

export default function Footer()
{
// Déclaration des constantes.
const basePath = getBasePath();
const { t } = useTranslation();

// Déclaration des variables d'état.
Expand All @@ -25,7 +22,7 @@ export default function Footer()
const openOverlay = () =>
{
// On lance d'abord la musique de fond.
const audio = new Audio( `${ basePath }/assets/sounds/jazz.mp3` );
const audio = new Audio( `${ process.env.__NEXT_ROUTER_BASEPATH }/assets/sounds/jazz.mp3` );
audio.volume = 0.1;
audio.play();

Expand Down
5 changes: 1 addition & 4 deletions app/legacy/components/language-selector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@

import { useRouter } from "next/navigation";
import { useState, lazy, type MouseEvent } from "react";

import { getBasePath } from "@/utilities/NextRouter";
import { useTranslation } from "@/utilities/ClientTranslations";

const ScrollTop = lazy( () => import( "./scroll-top" ) );
Expand All @@ -17,7 +15,6 @@ export default function LanguageSelector()
// Déclaration des constantes.
const { t } = useTranslation();
const router = useRouter();
const basePath = getBasePath( true );

// Déclaration des variables d'état.
const [ firstTime, setFirstTime ] = useState( true );
Expand All @@ -39,7 +36,7 @@ export default function LanguageSelector()
}

// On enregistre ensuite la langue dans les cookies.
document.cookie = `NEXT_LANGUAGE=${ language }; path=${ basePath }`;
document.cookie = `NEXT_LANGUAGE=${ language }; path=${ process.env.__NEXT_ROUTER_BASEPATH }`;

// On actualise enfin la page en demandant le changement de langue.
router.replace( `?language=${ language }` );
Expand Down
4 changes: 1 addition & 3 deletions app/legacy/components/photo-gallery.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,10 @@ import type { PhotoAttributes } from "@/interfaces/Photo";
import ArrowLeft from "@/images/decorations/arrow_left.svg";
import ArrowRight from "@/images/decorations/arrow_right.svg";

import { getBasePath } from "@/utilities/NextRouter";

export default function PhotoGallery( { project, photos }: { project: string, photos: PhotoAttributes[]; } )
{
// Déclaration des constantes.
const assets = `${ getBasePath() }/assets/images/projects`;
const assets = `${ process.env.__NEXT_ROUTER_BASEPATH }/assets/images/projects`;
const length = photos.length - 1;

// Déclaration des variables d'état.
Expand Down
4 changes: 1 addition & 3 deletions app/legacy/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,13 @@ import TopWaves from "@/images/decorations/projects_waves_top_blue.svg";
import BottomWaves from "@/images/decorations/projects_waves_bottom_blue.svg";

// Importation des fonctions utilitaires.
import { getBasePath } from "@/utilities/NextRouter";
import { useTranslation } from "@/utilities/ServerTranslations";

// Affichage de la page.
export default async function Page()
{
// Déclaration des constantes.
const basePath = getBasePath();
const assets = `${ basePath }/assets/images/projects`;
const assets = `${ process.env.__NEXT_ROUTER_BASEPATH }/assets/images/projects`;
const { t } = await useTranslation();
const date = new Date();

Expand Down
6 changes: 1 addition & 5 deletions app/legacy/projects/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,14 @@ import Image from "next/image";
import { lazy } from "react";
import { Trans } from "react-i18next/TransWithoutContext";

// Importation des fonctions utilitaires.
import { getBasePath } from "@/utilities/NextRouter";

// Importation des composants.
const PhotoGallery = lazy( () => import( "../components/photo-gallery" ) );

// Affichage de la page.
export default async function Page()
{
// Déclaration des constantes.
const basePath = getBasePath();
const assets = `${ basePath }/assets/images`;
const assets = `${ process.env.__NEXT_ROUTER_BASEPATH }/assets/images`;

// Affichage du rendu HTML de la page.
return (
Expand Down
4 changes: 1 addition & 3 deletions app/legacy/skills/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,13 @@ import { Trans } from "react-i18next/TransWithoutContext";
import Certificate from "@/images/skills/certificate.svg";

// Importation des fonctions utilitaires.
import { getBasePath } from "@/utilities/NextRouter";
import { useTranslation } from "@/utilities/ServerTranslations";

// Affichage de la page.
export default async function Page()
{
// Déclaration des constantes.
const basePath = getBasePath();
const assets = `${ basePath }/assets/images/skills`;
const assets = `${ process.env.__NEXT_ROUTER_BASEPATH }/assets/images/skills`;
const { t } = await useTranslation();

// Affichage du rendu HTML de la page.
Expand Down
2 changes: 2 additions & 0 deletions app/styles/legacy.scss
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,8 @@ h2 a, article a, form a, li > a, footer button
{
margin: 0;
display: inline;
padding: 0 0.25rem;
line-height: 1.75rem;
background-color: $deprecated-box-color;
}
}
17 changes: 0 additions & 17 deletions utilities/NextRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,6 @@
import { ReadonlyHeaders } from "next/dist/server/web/spec-extension/adapters/headers";
import { ReadonlyRequestCookies } from "next/dist/server/web/spec-extension/adapters/request-cookies";

//
// Récupération du répertoire de base de l'application.
// Note : ceci n'est pas encore implémenté dans le routeur de Next.js.
// Source : https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#step-5-migrating-routing-hooks
//
export const getBasePath = ( trailingSlash?: boolean ) =>
{
const basePath = new URL( process.env.NEXT_PUBLIC_URL ?? "" ).pathname;

if ( trailingSlash )
{
return basePath.endsWith( "/" ) ? basePath : `${ basePath }/`;
}

return basePath.endsWith( "/" ) ? basePath.slice( 0, -1 ) : basePath;
};

//
// Récupération de la langue sélectionnée par l'utilisateur.
// Note : ceci n'est plus implémenté dans le routeur de Next.js.
Expand Down

0 comments on commit 03e7fab

Please sign in to comment.