How to render pdf file in Nextjs - next.js

I'm trying to render pdf in nextjs project with react-pdf but I'm getting this error
pdf.js?8919:19293 GET http://localhost:5000/Technical-Catalogue.pdf net::ERR_BLOCKED_BY_CLIENT
and than Failed to load PDF file
import { Document, Page, pdfjs } from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist#${pdfjs.version}/build/pdf.worker.min.js`;
export default function Catalogue() {
return (
<Container>
<Document
file="/Technical-Catalogue.pdf"
>
<Page />
</Document>
</Container>
);
}
next.config.js
/** #type {import('next').NextConfig} */
const { withSuperjson } = require("next-superjson");
const { i18n } = require("./next-i18next.config");
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
i18n,
compiler: {
emotion: {
sourceMap: true,
autoLabel: "always",
labelFormat: "[filename]",
},
},
env: {
BASE_URL: process.env.BASE_URL || process.env.NEXT_PUBLIC_BASE_URL,
MEILI_HOST: process.env.NEXT_PUBLIC_BASE_URL_MEILI_HOST,
MEILI_API_KEY: process.env.NEXT_PUBLIC_BASE_URL_MEILI_API_KEY,
},
images: {
domains: ["localhost"],
deviceSizes: [670, 750, 828, 1080, 1224, 1920, 2048, 3840],
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
},
webpack: (
config,
{ buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
) => {
config.resolve.fallback = {
process: require.resolve("process/browser"),
zlib: require.resolve("browserify-zlib"),
stream: require.resolve("stream-browserify"),
util: require.resolve("util"),
buffer: require.resolve("buffer"),
asset: require.resolve("assert"),
};
config.plugins.push(
new webpack.ProvidePlugin({
Buffer: ["buffer", "Buffer"],
process: "process/browser",
})
);
return config
},
};
module.exports = withSuperjson()(nextConfig);
What should I do?

Related

Error when use remote components with hooks and module federations with nextjs

I receive this error when use hooks in component from remote app when
enter image description here
i use now nextjs13 with module federations
how to resolve this
enter code here
my component remote app
'use client'
import { useState } from 'react'
export default function Button() {
const [count, setCount] = useState(0)
return (
<div>
<button onClick={() => setCount(count + 1)}>adicionar</button>
<h1>{count}</h1>
</div>
)
}
my component in host
'use client'
import dynamic from 'next/dynamic'
import React, { useState } from 'react'
const RemoteComponent = dynamic({
loader: async () => {
const { default: RemoteComponent } = await import('front_login/Button')
return () => <RemoteComponent />
},
})
export default function Auth() {
return (
<>
<RemoteComponent />
</>
)
}
my next-config.js in host
const { NextFederationPlugin } = require('#module-federation/nextjs-mf')
/** #type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
experimental: {
appDir: true,
},
webpack: (config, options) => {
const { isServer } = options
Object.assign(config.experiments, { topLevelAwait: true })
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300,
}
config.plugins.push(
new NextFederationPlugin({
name: 'front_gateway',
remotes: {
front_login: `front_login#${process.env.FRONT_LOGIN}/_next/static/${
isServer ? 'ssr' : 'chunks'
}/remoteEntry.js`,
},
filename: 'static/chunks/remoteEntry.js',
shared: {
'styled-components': {
requiredVersion: false,
eager: true,
singleton: true,
},
},
}),
)
return config
},
}
module.exports = nextConfig
my next config in remote app
/** #type {import('next').NextConfig} */
const { NextFederationPlugin } = require('#module-federation/nextjs-mf')
const nextConfig = {
output: 'standalone',
experimental: {
appDir: true,
},
webpack: (config, options) => {
const { isServer } = options
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300,
}
config.plugins.push(
new NextFederationPlugin({
name: 'front_login',
remotes: {
front_gateway: `front_gateway#${
process.env.FRONT_GATEWAY
}/_next/static/${isServer ? 'ssr' : 'chunks'}/remoteEntry.js`,
},
filename: 'static/chunks/remoteEntry.js',
exposes: {
'./Button': './src/app/components/Button/button.tsx',
'./Doidao': './src/app/doidao/page.tsx',
},
shared: {
'styled-components': {
singleton: true,
eager: true,
requiredVersion: false,
},
},
}),
)
return config
},
}
module.exports = nextConfig
Please i need help to fix this
When use remote component in remote app, work with success but in host not working

How can I set Global Variables, that are not so secret?

I'm working on a NextJS website project that someone else will be working on too, when I'm done. He's pulling this project from time to time via Github, so I can show him how far I've come with our website.
I realized, that I want to set some global variables, like the links to our social media profiles, so that we could change them at one place, if something should change in the future. I did this with .env until now, but it contains secret variables as well. So I need to tell my collegue everytime I change something, how he needs to update it manually.
I tried it with setting ENVs in the next.config.js, but it won't work? I always get an undefined :(
This is my next.config.js
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
/** #type {import('next').NextConfig} */
const path = require('path');
const withPWA = require('next-pwa')({
dest: 'public',
disable: process.env.NODE_ENV === 'development',
sw: 'sw.js'
});
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
trailingSlash: false,
webpackDevMiddleware: config => {
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300
}
return config
},
sassOptions: {
includePaths: [path.join(__dirname, 'styles')]
},
experimental: {
images: {
layoutRaw: true
}
},
images: {
/*unoptimized: true - for static export!*/
/*deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
formats: ['image/webp']*/
},
env: {
NEXT_PUBLIC_TESTURL: "https://testurl.com"
}
};
module.exports = withBundleAnalyzer(withPWA({nextConfig}));
This is my page
export default function Page() {
console.log(process.env.NEXT_PUBLIC_TESTURL);
return (
<></>
)
}
This is something basic, right? What am I doing wrong?
I really appreciate your help!

how to setup antd less support with nextjs 12

im trying to setup nextjs 12 with ant design antd and in next.config.js when i try to setup withAntdLess it gives type error
Type '{}' is missing the following properties from type '{ esModule: boolean; sourceMap: boolean; modules: { mode: string; }; }': esModule, sourceMap, modules
although all props are optional according to next-plugin-antd-less docs
next.config.js file:
// #ts-check
// next.config.js
const withAntdLess = require('next-plugin-antd-less');
/**
* #type {import('next').NextConfig}
**/
module.exports =withAntdLess({
cssLoaderOptions: {},
// Other Config Here...
webpack(config) {
return config;
},
reactStrictMode: true,
});
I solved it using next-with-less https://github.com/elado/next-with-less
next.config.js
const withLess = require('next-with-less');
const lessToJS = require('less-vars-to-js');
const themeVariables = lessToJS(
fs.readFileSync(
path.resolve(__dirname, './public/styles/custom.less'),
'utf8'
)
);
module.exports = withLess({
...
lessLoaderOptions: {
lessOptions: {
javascriptEnabled: true,
modifyVars: themeVariables, // make your antd custom effective
localIdentName: '[path]___[local]___[hash:base64:5]',
},
},
...
})
Import your custom less file on top off the file _app.jsx
import 'public/styles/custom.less';
...
Import the default Antd less file on your custom less file: (in my case public/styles/custom.less)
#import "~antd/dist/antd.less";
....
Extra notes:
If you have an old implementation of Antd, you should remove the integration in your .babelrc
[
"import",
{
"libraryName": "antd",
"libraryDirectory": "lib",
"style": true
}
],
If you have an old implementation of Antd, you should remove the integration in your webpack zone in your next.config.js
if (isServer) {
const antStyles = /antd\/.*?\/style.*?/;
const origExternals = [...config.externals];
config.externals = [
(context, request, callback) => {
if (request.match(antStyles)) return callback();
if (typeof origExternals[0] === 'function') {
origExternals[0](context, request, callback);
} else {
callback();
}
},
...(typeof origExternals[0] === 'function' ? [] : origExternals),
];
config.module.rules.unshift({
test: antStyles,
use: 'null-loader',
});
}

adding export script to an existing next.config.js

I'm following Microsoft's Tutorial:
Deploy static-rendered Next.js websites on Azure Static Web Apps
The problem is, I'm trying to add to my next.config.js file this code:
const data = require('./utils/projectsData');
module.exports = {
trailingSlash: true,
exportPathMap: async function () {
const { projects } = data;
const paths = {
'/': { page: '/' },
};
projects.forEach((project) => {
paths[`/project/${project.slug}`] = {
page: '/project/[path]',
query: { path: project.slug },
};
});
return paths;
},
};
but my next.config.js already has some existing content:
require('dotenv').config()
const withFonts = require('next-fonts')
module.exports = withFonts({
serverRuntimeConfig: {},
trailingSlash: true,
exportPathMap: function() {
return {
'/': { page: '/' }
};
},
publicRuntimeConfig: {
API_URL: process.env.API_URL,
PORT: process.env.PORT || 3000,
PUBLISHABLE_KEY: process.env.PUBLISHABLE_KEY,
},
})
how can I combine them?
Just combine them like that?
require('dotenv').config()
const data = require('./utils/projectsData'); // Add this line
const withFonts = require('next-fonts')
module.exports = withFonts({
serverRuntimeConfig: {},
trailingSlash: true,
// And override this key
exportPathMap: async function () {
const { projects } = data;
const paths = {
'/': { page: '/' },
};
projects.forEach((project) => {
paths[`/project/${project.slug}`] = {
page: '/project/[path]',
query: { path: project.slug },
};
});
return paths;
},
publicRuntimeConfig: {
API_URL: process.env.API_URL,
PORT: process.env.PORT || 3000,
PUBLISHABLE_KEY: process.env.PUBLISHABLE_KEY,
},
})

Error: Invalid src prop on `next/image`, hostname "res.cloudinary.com" is not configured under images in your `next.config.js`

I'm creating an array of objects where I have an image src property whose name is coverSrc, and I'm exporting & importing it into my main component. In my main component, I m using the Material UI CardMedia component to display images. but it gives me the following error:
Invalid src prop on next/image, hostname "res.cloudinary.com" is not configured under images in your next.config.js
data.js
export const dataList = [
{
id: 1,
title: "Dim Sums",
serviceTime: "24-30min",
deliveryFee: 1.5,
category: "dish",
cuisine: "chinese",
rating: 2,
price: 4100,
coverSrc: "https://res.cloudinary.com/arifscloud/image/upload/v1625119382/image_apxesv.png",
},
{
id: 2,
title: "Dim loups",
serviceTime: "22-35min",
deliveryFee: 1.3,
category: "dish",
cuisine: "italian",
rating: 3,
price: 3100,
coverSrc: "https://res.cloudinary.com/arifscloud/image/upload/v1627596941/image_apiop.png",
},
]
ListItem.jsx
import {
Card,
CardHeader,
Avatar,
CardMedia,
CardContent,
Typography,
} from "#material-ui/core";
import React from "react";
import useStyles from "../../../styles/style.js";
import Image from "next/image"
const ListItem = ({
item: { coverSrc, title, price, deliveryFee, serviceTime, rating },
}) => {
const classes = useStyles();
return (
<Card className={classes.listItemMainDiv}>
<CardHeader
avatar={
<Avatar aria-label="recipe" className={classes.ratingAvatar}>
{rating}
</Avatar>
}
title={title}
/>
<CardMedia className={classes.media} title="List item" >
<Image src={coverSrc} layout="fill" alt="image"/>
</CardMedia>
<CardContent>
<Typography variant="body2" color="textSecondary" component="p" gutterBottom>
Delivery Fee ${deliveryFee}
</Typography>
</CardContent>
<div className={classes.cardFooter}>
<Typography>{serviceTime}</Typography>
<Typography>{price}</Typography>
</div>
</Card>
);
};
export default ListItem;
next.config.js
// next.config.js
module.exports = {
images: {
domains: ["res.cloudinary.com"],
},
}
I think import from array of object's property coverSrc there is some problem.
Can anyone help me to figure it out? How can I export coverSrc property from an array of objects?
Add the domain to your next.config.js like this:
module.exports = {
reactStrictMode: true,
images: {
domains: ['res.cloudinary.com'],
},
}
Important!: Make sure you restart your server each time you change the config file.
Change the extension of next.config file to js, not cjs or ts
This seem to work for me:
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
optimizeFonts: true,
images: {
remotePatterns: [
{
protocol: "https",
hostname: "res.cloudinary.com",
},
],
minimumCacheTTL: 1500000,
},
};
module.exports = nextConfig;
Possible Ways to Fix It
Add the protocol, hostname, port, and pathname to the images.remotePatterns config in next.config.js:
// next.config.js
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'res.cloudinary.com',
// You can add these as well
// port: '',
// pathname: 'arifscloud/image/upload/**',
},
],
},
}
If you are using an older version of Next.js prior to 12.3.0, you can use images.domains instead:
// next.config.js
module.exports = {
images: {
domains: ['res.cloudinary.com'],
},
}
For me, in next.config.js,
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
domains: [ "abc.def.org", ]
},
}
module.exports = nextConfig
and then in my Image tag
<Image
unoptimized // <- for image caching, else error
src={profile.picture}
alt={profile.picture || "IMG"}
width={60}
height={60}
/>

Resources