Skip to content

Commit

Permalink
Removed custom support for base path configuration with NextJS
Browse files Browse the repository at this point in the history
  • Loading branch information
FlorianLeChat committed Dec 21, 2024
1 parent f85157a commit e5e2bf5
Show file tree
Hide file tree
Showing 12 changed files with 36 additions and 68 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"space-in-parens": ["error", "always"],
"no-param-reassign": ["error", { "props": false }],
"operator-linebreak": ["error", "before", { "overrides": { "=": "after" } }],
"no-underscore-dangle": ["error", { "allow": ["_def", "_count", "__NEXT_ROUTER_BASEPATH"] }], // https://github.com/vercel/next.js/issues/52201#issuecomment-1620629437
"no-underscore-dangle": ["error", { "allow": ["_def", "_count"] }], // https://github.com/vercel/next.js/issues/52201#issuecomment-1620629437
"object-curly-newline": ["error", { "ImportDeclaration": { "minProperties": 0 }}],
"array-bracket-spacing": ["error", "always"],
"template-curly-spacing": ["error", "always"],
Expand Down
5 changes: 1 addition & 4 deletions app/[locale]/components/cookie-consent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,7 @@ export default function CookieConsent()
// Paramètres internes des cookies.
cookie: {
name: "NEXT_COOKIE",
path:
process.env.__NEXT_ROUTER_BASEPATH === ""
? "/"
: process.env.__NEXT_ROUTER_BASEPATH
path: "/"
},

// Paramètres de l'interface utilisateur.
Expand Down
20 changes: 9 additions & 11 deletions app/[locale]/components/notification.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,21 +40,19 @@ export default function Notifications()
const locale = useLocale();
const formMessages = useTranslations( "form" );
const modalMessages = useTranslations( "modals.notifications" );
const [ isOpen, setOpen ] = useState( false );
const [ isLoading, setLoading ] = useState( false );
const [ isOpen, setIsOpen ] = useState( false );
const [ isLoading, setIsLoading ] = useState( false );
const [ unreadCount, setUnreadCount ] = useState( 0 );
const [ notifications, setNotifications ] = useState<Notification[]>( [] );

// Récupération des notifications depuis l'API.
const fetchNotifications = useCallback( async () =>
{
// Activation de l'état de chargement.
setLoading( true );
setIsLoading( true );

// Lancement de la requête HTTP et vérification de la réponse.
const response = await fetch(
`${ process.env.__NEXT_ROUTER_BASEPATH }/api/user/notifications`
);
const response = await fetch( "/api/user/notifications" );

if ( !response.ok )
{
Expand All @@ -77,7 +75,7 @@ export default function Notifications()
setUnreadCount( ( count ) => Math.min( data.length, count + filter.length ) );

// Désactivation de l'état de chargement.
setLoading( false );
setIsLoading( false );

// Vérification de l'existence de l'API de notifications.
if ( typeof Notification !== "undefined" && filter.length > 0 )
Expand Down Expand Up @@ -131,19 +129,19 @@ export default function Notifications()
const submitClearing = async () =>
{
// Activation de l'état de chargement.
setLoading( true );
setIsLoading( true );

// Envoi de la requête au serveur et
// traitement de la réponse.
const state = await serverAction( updateReadState, new FormData(), formMessages );

// Fin de l'état de chargement.
setLoading( false );
setIsLoading( false );

if ( state )
{
// Fermeture de la boîte de dialogue.
setOpen( false );
setIsOpen( false );

// Marquage de toutes les notifications
// comme lues.
Expand Down Expand Up @@ -190,7 +188,7 @@ export default function Notifications()
{
if ( !isLoading )
{
setOpen( state );
setIsOpen( state );
}
}}
>
Expand Down
2 changes: 1 addition & 1 deletion app/[locale]/components/recaptcha.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export default function Recaptcha()
const body = new FormData();
body.append( "1_recaptcha", token );

fetch( `${ process.env.__NEXT_ROUTER_BASEPATH }/api/recaptcha`, {
fetch( "/api/recaptcha", {
body,
method: "POST"
} );
Expand Down
2 changes: 1 addition & 1 deletion app/[locale]/dashboard/actions/file-upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ export async function uploadFiles(
// fichiers sous format JSON pour pouvoir les envoyer
// à travers le réseau vers les composants clients.
// Source : https://github.com/vercel/next.js/issues/47447
const path = `${ process.env.__NEXT_ROUTER_BASEPATH }/d/${ fileId }${
const path = `/d/${ fileId }${
preferences.extension ? extension : ""
}`;
const versions = await prisma.version.findMany( {
Expand Down
6 changes: 2 additions & 4 deletions app/[locale]/dashboard/components/data-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import Pagination from "./pagination";
import FileUpload from "./file-upload";
import ColumnToggle from "./column-toggle";

export default function DataTable( { data }: { data: FileAttributes[] } )
export default function DataTable( { data }: Readonly<{ data: FileAttributes[] }> )
{
// Déclaration des variables d'état.
const messages = useMessages() as {
Expand Down Expand Up @@ -117,9 +117,7 @@ export default function DataTable( { data }: { data: FileAttributes[] } )

// Affichage du rendu HTML du composant.
return (
<SessionProvider
basePath={`${ process.env.__NEXT_ROUTER_BASEPATH }/api/user/auth`}
>
<SessionProvider basePath="/api/user/auth">
{/* Filtrage et tri des données */}
<div className="mb-4 flex items-center gap-2">
{/* Filtrage par nom */}
Expand Down
18 changes: 8 additions & 10 deletions app/[locale]/dashboard/components/share-manager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@ export default function ShareManager( {
file,
states,
disabled
}: {
}: Readonly<{
file: FileAttributes;
states: TableMeta<FileAttributes>;
disabled: boolean;
} )
}> )
{
// Déclaration des constantes.
const fetcher = ( url: string ) => fetch( url ).then( ( res ) => res.json() ) as Promise<User[]>;
Expand All @@ -63,14 +63,12 @@ export default function ShareManager( {
const session = useSession();
const formMessages = useTranslations( "form" );
const modalMessages = useTranslations( "modals.share-manager" );
const [ isOpen, setOpen ] = useState( false );
const [ isOpen, setIsOpen ] = useState( false );
const [ search, setSearch ] = useState( "" );
const [ loading, setLoading ] = useState( false );
const [ isCopied, setCopied ] = useState( false );
const [ isCopied, setIsCopied ] = useState( false );
const { data, error, isLoading } = useSWR<User[]>(
search !== ""
? `${ process.env.__NEXT_ROUTER_BASEPATH }/api/user/search/${ search }`
: null,
search !== "" ? `/api/user/search/${ search }` : null,
fetcher
);

Expand Down Expand Up @@ -240,7 +238,7 @@ export default function ShareManager( {
{
if ( !loading )
{
setOpen( state );
setIsOpen( state );
}
}}
>
Expand Down Expand Up @@ -282,10 +280,10 @@ export default function ShareManager( {
onClick={() =>
{
// Déclaration de la copie du lien.
setCopied( true );
setIsCopied( true );

// Réinitialisation de l'état de copie.
setTimeout( () => setCopied( false ), 1500 );
setTimeout( () => setIsCopied( false ), 1500 );

// Copie du lien dans le presse-papiers.
navigator.clipboard.writeText(
Expand Down
4 changes: 1 addition & 3 deletions app/[locale]/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,7 @@ async function getFiles(): Promise<FileAttributes[]>
files.map( async ( file ) =>
{
const info = parse( file.name );
const path = `${ process.env.__NEXT_ROUTER_BASEPATH }/d/${ file.id }${
extension ? info.ext : ""
}`;
const path = `/d/${ file.id }${ extension ? info.ext : "" }`;

return {
uuid: file.id,
Expand Down
7 changes: 2 additions & 5 deletions app/[locale]/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,7 @@ export async function generateMetadata(): Promise<
// On détermine après certaines métadonnées récurrentes.
const banner = `https://opengraph.githubassets.com/${ commits.sha }/${ repository.full_name }`;
const title = repository.name.replaceAll( "-", " " );
const url =
process.env.NEXT_PUBLIC_ENV === "production"
? repository.homepage
: `http://localhost:3000${ process.env.__NEXT_ROUTER_BASEPATH }`;
const url = process.env.NEXT_PUBLIC_ENV === "production" ? repository.homepage : "http://localhost:3000";

// On retourne également les métadonnées récupérées récemment
// avant de les enregistrer dans un fichier JSON.
Expand Down Expand Up @@ -312,7 +309,7 @@ export default async function Layout( {
className="fixed -z-10 hidden size-full object-none opacity-10 dark:block"
>
<source
src={`${ process.env.__NEXT_ROUTER_BASEPATH }/assets/videos/background.mp4`}
src="/assets/videos/background.mp4"
type="video/mp4"
/>
</video>
Expand Down
29 changes: 7 additions & 22 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default async function middleware( request: NextRequest )
// du fichier à partir de son identifiant.
const data = await fetch(
new URL(
`${ process.env.__NEXT_ROUTER_BASEPATH }/api/file/${ identifier }/${ request.nextUrl.search }`,
`/api/file/${ identifier }/${ request.nextUrl.search }`,
request.url
),
{ headers: request.headers }
Expand All @@ -60,7 +60,7 @@ export default async function middleware( request: NextRequest )

const content = await fetch(
new URL(
`${ process.env.__NEXT_ROUTER_BASEPATH }/api/public/files/${ file.userId }/${ file.id }/${ file.versions[ 0 ].id }.${ extension }`,
`/api/public/files/${ file.userId }/${ file.id }/${ file.versions[ 0 ].id }.${ extension }`,
data.url
),
{ headers }
Expand Down Expand Up @@ -152,13 +152,9 @@ export default async function middleware( request: NextRequest )
// des robots d'indexation.
if ( request.nextUrl.pathname.startsWith( "/avatars/" ) )
{
const data = await fetch(
new URL(
`${ process.env.__NEXT_ROUTER_BASEPATH }/api/user/session`,
request.url
),
{ headers: request.headers }
);
const data = await fetch( new URL( "/api/user/session", request.url ), {
headers: request.headers
} );

if ( data.ok )
{
Expand All @@ -169,10 +165,7 @@ export default async function middleware( request: NextRequest )
headers.set( "X-Auth-Secret", process.env.AUTH_SECRET ?? "" );

const content = await fetch(
new URL(
`${ process.env.__NEXT_ROUTER_BASEPATH }/api/public/${ session.image }`,
data.url
),
new URL( `/api/public/${ session.image }`, data.url ),
{ headers }
);

Expand Down Expand Up @@ -266,12 +259,4 @@ export const config = {
"/",
"/((?!api/admin|api/user|api/version|api/versions|api/file|api/public|api/files|monitoring|assets|locales|_next|_vercel|sitemap.xml|manifest.webmanifest).*)"
]
};

if ( process.env.__NEXT_ROUTER_BASEPATH )
{
// Ajout du support du chemin de base de NextJS pour le routage
// effectué par le mécanisme de gestion des langues et traductions.
// Source : https://next-intl-docs.vercel.app/docs/routing/middleware#base-path
config.matcher.push( process.env.__NEXT_ROUTER_BASEPATH );
}
};
1 change: 0 additions & 1 deletion next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ const nextConfig: NextConfig = withNextIntl( {
)
}
},
basePath: "",
async redirects()
{
return [
Expand Down
8 changes: 3 additions & 5 deletions utilities/next-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth( () => ( {
session: {
strategy: process.env.NEXT_PUBLIC_ENV === "production" ? "database" : "jwt"
},
basePath: process.env.AUTH_URL
? undefined
: `${ process.env.__NEXT_ROUTER_BASEPATH }/api/user/auth`,
basePath: process.env.AUTH_URL ? undefined : "/api/user/auth",
trustHost: true,
callbacks: {
// Gestion des données du jeton JWT (environnement de test et de développement).
Expand Down Expand Up @@ -85,7 +83,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth( () => ( {
if ( avatar.find( ( file ) => file.includes( token.id ) ) )
{
// Définition de l'avatar personnalisé de l'utilisateur.
token.image = `${ process.env.__NEXT_ROUTER_BASEPATH }/avatars/${ avatar }`;
token.image = `/avatars/${ avatar }`;
}
}
}
Expand Down Expand Up @@ -139,7 +137,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth( () => ( {

if ( avatar.find( ( file ) => file.includes( user.id ) ) )
{
session.user.image = `${ process.env.__NEXT_ROUTER_BASEPATH }/avatars/${ avatar }`;
session.user.image = `/avatars/${ avatar }`;
}
}
}
Expand Down

0 comments on commit e5e2bf5

Please sign in to comment.