##Diferenças entre next.config.js e next.config.mjs
next.connfig.js:
- Utiliza o sistema de módulos CommonJS.
- Este é o formato padrão de arquivo de configuração do Next.js.
- Utiliza a sintaxe
requirepara importar módulos emodule.exportspara expotrar objetos.
next.config.mjs:
- Utiliza o sistema de módulos ES Modules (ESM).
- Oferece sintaxe e funcionalidades mais modernas.
- Utiliza a sintaxe
importpara importar módulos eexportpara exportar objetos.
Soluções
O exemplo abaixo utiliza
next.config.mjs, mas o princípio é o mesmo paranext.config.js
Cofniguração do Next.js
next.config.mjs
/** @type {import('next').NextConfig} */
const config = {
reactStrictMode: false,
};
// Configuração de cabeçalhos HTTP
config.headers = async () => {
return [
{
source: '/api/:path*',
headers: [
{ key: 'Access-Control-Allow-Credentials', value: 'true' },
{ key: 'Access-Control-Allow-Origin', value: '*' },
{ key: 'Access-Control-Allow-Methods', value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT' },
]
}
]
}
// Configuração de proxy/reescrita de rotas
config.rewrites = async () => {
return [
{
source: '/api/proxy/:path*',
destination: 'https://api.externo.com/:path*',
},
]
}
export default config;
next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/api/proxy/:path*',
destination: 'https://api.externo.com/:path*'
}
];
},
async headers() {
return [
{
source: '/api/:path*',
headers: [
{ key: 'Access-Control-Allow-Credentials', value: 'true' },
{ key: 'Access-Control-Allow-Origin', value: '*' },
{ key: 'Access-Control-Allow-Methods', value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT' },
{ key: 'Access-Control-Allow-Headers', value: 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version' },
],
},
];
},
}
Configuração do Axios
- instance.ts
import Axios, {
type AxiosInstance,
type AxiosRequestConfig
} from "axios";
const config: AxiosRequestConfig = {
baseURL: '/api/proxy',
timeout: 15000,
headers: {
'Content-Type': 'application/json'
},
};
const apiClient: AxiosInstance = Axios.create(config);
export default apiClient;